code
stringlengths
2
1.05M
var cluster = require('cluster'); var sysUtils = require('./utils'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('fork', function(worker) { sysUtils.log('Cluster: worker ' + worker.process.pid + ' started'); }); cluster.on('exit', function(worker, code, signal) { sysUtils.log('Cluster: worker ' + worker.process.pid + ' died (code: ' + code + '), restarting...'); cluster.fork(); }); } else { require('./server'); if (CONFIG.CLUSTER_MAX_CPU_LOAD_TIME_IN_SECONDS && CONFIG.CLUSTER_MAX_CPU_LOAD_IN_PERCENT) { var usage = require('usage'); var stats = []; setInterval(function() { usage.lookup(process.pid, function(error, result) { if (error) { console.error('Error getting process stats', err); return; } stats.push(result.cpu); if (stats.length > CONFIG.CLUSTER_MAX_CPU_LOAD_TIME_IN_SECONDS) { stats.shift(); var sum = 0; stats.forEach(function(cpu) { sum += cpu; }); var averageCpu = sum / stats.length; if (averageCpu > CONFIG.CLUSTER_MAX_CPU_LOAD_IN_PERCENT) { sysUtils.log('Cluster: worker ' + process.pid + ' used too much CPU (' + averageCpu + '%), exiting...'); process.exit(1); } } }); }, 1000); } if (CONFIG.CLUSTER_WORKER_RESTART_ON_MEMORY_USED) { setInterval(function() { var mem = process.memoryUsage().rss; if (mem > CONFIG.CLUSTER_WORKER_RESTART_ON_MEMORY_USED) { sysUtils.log('Cluster: worker ' + process.pid + ' used too much memory (' + Math.round(mem / (1024*1024)) + ' MB), exiting...'); process.exit(1); } }, 1000); } }
/* * * * (c) 2010-2020 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import Chart from '../parts/Chart.js'; import H from '../parts/Globals.js'; var doc = H.doc; import U from '../parts/Utilities.js'; var addEvent = U.addEvent, extend = U.extend, merge = U.merge, objectEach = U.objectEach, pick = U.pick; /* eslint-disable no-invalid-this, valid-jsdoc */ /** * @private */ function stopEvent(e) { if (e) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } } /** * The MapNavigation handles buttons for navigation in addition to mousewheel * and doubleclick handlers for chart zooming. * * @private * @class * @name MapNavigation * * @param {Highcharts.Chart} chart * The Chart instance. */ function MapNavigation(chart) { this.init(chart); } /** * Initialize function. * * @function MapNavigation#init * * @param {Highcharts.Chart} chart * The Chart instance. * * @return {void} */ MapNavigation.prototype.init = function (chart) { this.chart = chart; chart.mapNavButtons = []; }; /** * Update the map navigation with new options. Calling this is the same as * calling `chart.update({ mapNavigation: {} })`. * * @function MapNavigation#update * * @param {Highcharts.MapNavigationOptions} [options] * New options for the map navigation. * * @return {void} */ MapNavigation.prototype.update = function (options) { var chart = this.chart, o = chart.options.mapNavigation, buttonOptions, attr, states, hoverStates, selectStates, outerHandler = function (e) { this.handler.call(chart, e); stopEvent(e); // Stop default click event (#4444) }, mapNavButtons = chart.mapNavButtons; // Merge in new options in case of update, and register back to chart // options. if (options) { o = chart.options.mapNavigation = merge(chart.options.mapNavigation, options); } // Destroy buttons in case of dynamic update while (mapNavButtons.length) { mapNavButtons.pop().destroy(); } if (pick(o.enableButtons, o.enabled) && !chart.renderer.forExport) { objectEach(o.buttons, function (button, n) { buttonOptions = merge(o.buttonOptions, button); // Presentational if (!chart.styledMode) { attr = buttonOptions.theme; attr.style = merge(buttonOptions.theme.style, buttonOptions.style // #3203 ); states = attr.states; hoverStates = states && states.hover; selectStates = states && states.select; } button = chart.renderer .button(buttonOptions.text, 0, 0, outerHandler, attr, hoverStates, selectStates, 0, n === 'zoomIn' ? 'topbutton' : 'bottombutton') .addClass('highcharts-map-navigation highcharts-' + { zoomIn: 'zoom-in', zoomOut: 'zoom-out' }[n]) .attr({ width: buttonOptions.width, height: buttonOptions.height, title: chart.options.lang[n], padding: buttonOptions.padding, zIndex: 5 }) .add(); button.handler = buttonOptions.onclick; // Stop double click event (#4444) addEvent(button.element, 'dblclick', stopEvent); mapNavButtons.push(button); // Align it after the plotBox is known (#12776) var bo = buttonOptions; var un = addEvent(chart, 'load', function () { button.align(extend(bo, { width: button.width, height: 2 * button.height }), null, bo.alignTo); un(); }); }); } this.updateEvents(o); }; /** * Update events, called internally from the update function. Add new event * handlers, or unbinds events if disabled. * * @function MapNavigation#updateEvents * * @param {Highcharts.MapNavigationOptions} options * Options for map navigation. * * @return {void} */ MapNavigation.prototype.updateEvents = function (options) { var chart = this.chart; // Add the double click event if (pick(options.enableDoubleClickZoom, options.enabled) || options.enableDoubleClickZoomTo) { this.unbindDblClick = this.unbindDblClick || addEvent(chart.container, 'dblclick', function (e) { chart.pointer.onContainerDblClick(e); }); } else if (this.unbindDblClick) { // Unbind and set unbinder to undefined this.unbindDblClick = this.unbindDblClick(); } // Add the mousewheel event if (pick(options.enableMouseWheelZoom, options.enabled)) { this.unbindMouseWheel = this.unbindMouseWheel || addEvent(chart.container, typeof doc.onmousewheel === 'undefined' ? 'DOMMouseScroll' : 'mousewheel', function (e) { chart.pointer.onContainerMouseWheel(e); // Issue #5011, returning false from non-jQuery event does // not prevent default stopEvent(e); return false; }); } else if (this.unbindMouseWheel) { // Unbind and set unbinder to undefined this.unbindMouseWheel = this.unbindMouseWheel(); } }; // Add events to the Chart object itself extend(Chart.prototype, /** @lends Chart.prototype */ { /** * Fit an inner box to an outer. If the inner box overflows left or right, * align it to the sides of the outer. If it overflows both sides, fit it * within the outer. This is a pattern that occurs more places in * Highcharts, perhaps it should be elevated to a common utility function. * * @ignore * @function Highcharts.Chart#fitToBox * * @param {Highcharts.BBoxObject} inner * * @param {Highcharts.BBoxObject} outer * * @return {Highcharts.BBoxObject} * The inner box */ fitToBox: function (inner, outer) { [['x', 'width'], ['y', 'height']].forEach(function (dim) { var pos = dim[0], size = dim[1]; if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right // the general size is greater, fit fully to outer if (inner[size] > outer[size]) { inner[size] = outer[size]; inner[pos] = outer[pos]; } else { // align right inner[pos] = outer[pos] + outer[size] - inner[size]; } } if (inner[size] > outer[size]) { inner[size] = outer[size]; } if (inner[pos] < outer[pos]) { inner[pos] = outer[pos]; } }); return inner; }, /** * Highmaps only. Zoom in or out of the map. See also {@link Point#zoomTo}. * See {@link Chart#fromLatLonToPoint} for how to get the `centerX` and * `centerY` parameters for a geographic location. * * @function Highcharts.Chart#mapZoom * * @param {number} [howMuch] * How much to zoom the map. Values less than 1 zooms in. 0.5 zooms * in to half the current view. 2 zooms to twice the current view. If * omitted, the zoom is reset. * * @param {number} [centerX] * The X axis position to center around if available space. * * @param {number} [centerY] * The Y axis position to center around if available space. * * @param {number} [mouseX] * Fix the zoom to this position if possible. This is used for * example in mousewheel events, where the area under the mouse * should be fixed as we zoom in. * * @param {number} [mouseY] * Fix the zoom to this position if possible. * * @return {void} */ mapZoom: function (howMuch, centerXArg, centerYArg, mouseX, mouseY) { var chart = this, xAxis = chart.xAxis[0], xRange = xAxis.max - xAxis.min, centerX = pick(centerXArg, xAxis.min + xRange / 2), newXRange = xRange * howMuch, yAxis = chart.yAxis[0], yRange = yAxis.max - yAxis.min, centerY = pick(centerYArg, yAxis.min + yRange / 2), newYRange = yRange * howMuch, fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5, fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5, newXMin = centerX - newXRange * fixToX, newYMin = centerY - newYRange * fixToY, newExt = chart.fitToBox({ x: newXMin, y: newYMin, width: newXRange, height: newYRange }, { x: xAxis.dataMin, y: yAxis.dataMin, width: xAxis.dataMax - xAxis.dataMin, height: yAxis.dataMax - yAxis.dataMin }), zoomOut = (newExt.x <= xAxis.dataMin && newExt.width >= xAxis.dataMax - xAxis.dataMin && newExt.y <= yAxis.dataMin && newExt.height >= yAxis.dataMax - yAxis.dataMin); // When mousewheel zooming, fix the point under the mouse if (mouseX && xAxis.mapAxis) { xAxis.mapAxis.fixTo = [mouseX - xAxis.pos, centerXArg]; } if (mouseY && yAxis.mapAxis) { yAxis.mapAxis.fixTo = [mouseY - yAxis.pos, centerYArg]; } // Zoom if (typeof howMuch !== 'undefined' && !zoomOut) { xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false); yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false); // Reset zoom } else { xAxis.setExtremes(void 0, void 0, false); yAxis.setExtremes(void 0, void 0, false); } // Prevent zooming until this one is finished animating /* chart.holdMapZoom = true; setTimeout(function () { chart.holdMapZoom = false; }, 200); */ /* delay = animation ? animation.duration || 500 : 0; if (delay) { chart.isMapZooming = true; setTimeout(function () { chart.isMapZooming = false; if (chart.mapZoomQueue) { chart.mapZoom.apply(chart, chart.mapZoomQueue); } chart.mapZoomQueue = null; }, delay); } */ chart.redraw(); } }); // Extend the Chart.render method to add zooming and panning addEvent(Chart, 'beforeRender', function () { // Render the plus and minus buttons. Doing this before the shapes makes // getBBox much quicker, at least in Chrome. this.mapNavigation = new MapNavigation(this); this.mapNavigation.update(); }); H.MapNavigation = MapNavigation;
/* * * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import SeriesRegistry from '../../../Core/Series/SeriesRegistry.js'; var SMAIndicator = SeriesRegistry.seriesTypes.sma; import U from '../../../Core/Utilities.js'; var isArray = U.isArray, merge = U.merge; /* eslint-disable valid-jsdoc */ // Utils: /** * @private */ function accumulateAverage(points, xVal, yVal, i) { var xValue = xVal[i], yValue = yVal[i]; points.push([xValue, yValue]); } /** * @private */ function getTR(currentPoint, prevPoint) { var pointY = currentPoint, prevY = prevPoint, HL = pointY[1] - pointY[2], HCp = typeof prevY === 'undefined' ? 0 : Math.abs(pointY[1] - prevY[3]), LCp = typeof prevY === 'undefined' ? 0 : Math.abs(pointY[2] - prevY[3]), TR = Math.max(HL, HCp, LCp); return TR; } /** * @private */ function populateAverage(points, xVal, yVal, i, period, prevATR) { var x = xVal[i - 1], TR = getTR(yVal[i - 1], yVal[i - 2]), y; y = (((prevATR * (period - 1)) + TR) / period); return [x, y]; } /* eslint-enable valid-jsdoc */ /* * * * Class * * */ /** * The ATR series type. * * @private * @class * @name Highcharts.seriesTypes.atr * * @augments Highcharts.Series */ var ATRIndicator = /** @class */ (function (_super) { __extends(ATRIndicator, _super); function ATRIndicator() { var _this = _super !== null && _super.apply(this, arguments) || this; /* * * * Properties * * */ _this.data = void 0; _this.points = void 0; _this.options = void 0; return _this; } /* * * * Functions * * */ ATRIndicator.prototype.getValues = function (series, params) { var period = params.period, xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, xValue = xVal[0], yValue = yVal[0], range = 1, prevATR = 0, TR = 0, ATR = [], xData = [], yData = [], point, i, points; points = [[xValue, yValue]]; if ((xVal.length <= period) || !isArray(yVal[0]) || yVal[0].length !== 4) { return; } for (i = 1; i <= yValLen; i++) { accumulateAverage(points, xVal, yVal, i); if (period < range) { point = populateAverage(points, xVal, yVal, i, period, prevATR); prevATR = point[1]; ATR.push(point); xData.push(point[0]); yData.push(point[1]); } else if (period === range) { prevATR = TR / (i - 1); ATR.push([xVal[i - 1], prevATR]); xData.push(xVal[i - 1]); yData.push(prevATR); range++; } else { TR += getTR(yVal[i - 1], yVal[i - 2]); range++; } } return { values: ATR, xData: xData, yData: yData }; }; /** * Average true range indicator (ATR). This series requires `linkedTo` * option to be set. * * @sample stock/indicators/atr * ATR indicator * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @requires stock/indicators/indicators * @requires stock/indicators/atr * @optionparent plotOptions.atr */ ATRIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, { params: { period: 14 } }); return ATRIndicator; }(SMAIndicator)); SeriesRegistry.registerSeriesType('atr', ATRIndicator); /* * * * Default Export * * */ export default ATRIndicator; /** * A `ATR` series. If the [type](#series.atr.type) option is not specified, it * is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.atr * @since 6.0.0 * @product highstock * @excluding dataParser, dataURL * @requires stock/indicators/indicators * @requires stock/indicators/atr * @apioption series.atr */ ''; // to include the above in the js output
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; let _ = t => t, _t, _t2, _t3, _t4, _t5, _t6; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { deepmerge } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import { keyframes, css } from '@material-ui/styled-engine'; import capitalize from '../utils/capitalize'; import { darken, lighten } from '../styles/colorManipulator'; import useTheme from '../styles/useTheme'; import experimentalStyled from '../styles/experimentalStyled'; import useThemeProps from '../styles/useThemeProps'; import linearProgressClasses, { getLinearProgressUtilityClass } from './linearProgressClasses'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; const TRANSITION_DURATION = 4; // seconds const indeterminate1Keyframe = keyframes(_t || (_t = _` 0% { left: -35%; right: 100%; } 60% { left: 100%; right: -90%; } 100% { left: 100%; right: -90%; } `)); const indeterminate2Keyframe = keyframes(_t2 || (_t2 = _` 0% { left: -200%; right: 100%; } 60% { left: 107%; right: -8%; } 100% { left: 107%; right: -8%; } `)); const bufferKeyframe = keyframes(_t3 || (_t3 = _` 0% { opacity: 1; background-position: 0 -23px; } 60% { opacity: 0; background-position: 0 -23px; } 100% { opacity: 1; background-position: -200px -23px; } `)); const overridesResolver = (props, styles) => { const { styleProps } = props; return deepmerge(styles.root || {}, _extends({}, styles[`color${capitalize(styleProps.color)}`], styles[styleProps.variant], { [`& .${linearProgressClasses.dashed}`]: styleProps.variant === 'buffer' && _extends({}, styles.dashed, styles[`dashedColor${capitalize(styleProps.color)}`]), [`& .${linearProgressClasses.bar}`]: _extends({}, styles.bar, styles[`barColor${capitalize(styleProps.color)}`]), [`& .${linearProgressClasses.bar1Indeterminate}`]: (styleProps.variant === 'indeterminate' || styleProps.variant === 'query') && styles.bar1Indeterminate, [`& .${linearProgressClasses.bar1Determinate}`]: styleProps.variant === 'determinate' && styles.bar1Determinate, [`& .${linearProgressClasses.bar1Buffer}`]: styleProps.variant === 'buffer' && styles.bar1Buffer, [`& .${linearProgressClasses.bar2Indeterminate}`]: (styleProps.variant === 'indeterminate' || styleProps.variant === 'query') && styles.bar2Indeterminate, [`& .${linearProgressClasses.bar2Buffer}`]: styleProps.variant === 'buffer' && styles.bar2Buffer })); }; const useUtilityClasses = styleProps => { const { classes, variant, color } = styleProps; const slots = { root: ['root', `color${capitalize(color)}`, variant], dashed: ['dashed', `dashedColor${capitalize(color)}`], bar1: ['bar', `barColor${capitalize(color)}`, (variant === 'indeterminate' || variant === 'query') && 'bar1Indeterminate', variant === 'determinate' && 'bar1Determinate', variant === 'buffer' && 'bar1Buffer'], bar2: ['bar', variant !== 'buffer' && `barColor${capitalize(color)}`, variant === 'buffer' && `color${capitalize(color)}`, (variant === 'indeterminate' || variant === 'query') && 'bar2Indeterminate', variant === 'buffer' && 'bar2Buffer'] }; return composeClasses(slots, getLinearProgressUtilityClass, classes); }; const getColorShade = (theme, color) => theme.palette.mode === 'light' ? lighten(theme.palette[color].main, 0.62) : darken(theme.palette[color].main, 0.5); const LinearProgressRoot = experimentalStyled('span', {}, { name: 'MuiLinearProgress', slot: 'Root', overridesResolver })(({ styleProps, theme }) => _extends({ /* Styles applied to the root element. */ position: 'relative', overflow: 'hidden', display: 'block', height: 4, zIndex: 0, // Fix Safari's bug during composition of different paint. '@media print': { colorAdjust: 'exact' }, backgroundColor: getColorShade(theme, styleProps.color) }, styleProps.variant === 'buffer' && { backgroundColor: 'transparent' }, styleProps.variant === 'query' && { transform: 'rotate(180deg)' })); const LinearProgressDashed = experimentalStyled('span', {}, { name: 'MuiLinearProgress', slot: 'Dashed' })(({ styleProps, theme }) => { const backgroundColor = getColorShade(theme, styleProps.color); return { /* Styles applied to the additional bar element if `variant="buffer"`. */ position: 'absolute', marginTop: 0, height: '100%', width: '100%', backgroundImage: `radial-gradient(${backgroundColor} 0%, ${backgroundColor} 16%, transparent 42%)`, backgroundSize: '10px 10px', backgroundPosition: '0 -23px' }; }, css(_t4 || (_t4 = _` animation: ${0} 3s infinite linear; `), bufferKeyframe)); const LinearProgressBar1 = experimentalStyled('span', {}, { name: 'MuiLinearProgress', slot: 'Bar1' })(({ styleProps, theme }) => _extends({ /* Styles applied to the additional bar element if `variant="buffer"`. */ width: '100%', position: 'absolute', left: 0, bottom: 0, top: 0, transition: 'transform 0.2s linear', transformOrigin: 'left', backgroundColor: theme.palette[styleProps.color].main }, styleProps.variant === 'determinate' && { transition: `transform .${TRANSITION_DURATION}s linear` }, styleProps.variant === 'buffer' && { zIndex: 1, transition: `transform .${TRANSITION_DURATION}s linear` }), /* Styles applied to the bar1 element if `variant="indeterminate or query"`. */ ({ styleProps }) => (styleProps.variant === 'indeterminate' || styleProps.variant === 'query') && css(_t5 || (_t5 = _` width: auto; animation: ${0} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite; `), indeterminate1Keyframe)); const LinearProgressBar2 = experimentalStyled('span', {}, { name: 'MuiLinearProgress', slot: 'Bar2' })(({ styleProps, theme }) => _extends({ /* Styles applied to the additional bar element if `variant="buffer"`. */ width: '100%', position: 'absolute', left: 0, bottom: 0, top: 0, transition: 'transform 0.2s linear', transformOrigin: 'left' }, styleProps.variant !== 'buffer' && { backgroundColor: theme.palette[styleProps.color].main }, styleProps.variant === 'buffer' && { backgroundColor: getColorShade(theme, styleProps.color), transition: `transform .${TRANSITION_DURATION}s linear` }), /* Styles applied to the bar1 element if `variant="indeterminate or query"`. */ ({ styleProps }) => (styleProps.variant === 'indeterminate' || styleProps.variant === 'query') && css(_t6 || (_t6 = _` width: auto; animation: ${0} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite; `), indeterminate2Keyframe)); /** * ## ARIA * * If the progress bar is describing the loading progress of a particular region of a page, * you should use `aria-describedby` to point to the progress bar, and set the `aria-busy` * attribute to `true` on that region until it has finished loading. */ const LinearProgress = /*#__PURE__*/React.forwardRef(function LinearProgress(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiLinearProgress' }); const { className, color = 'primary', value, valueBuffer, variant = 'indeterminate' } = props, other = _objectWithoutPropertiesLoose(props, ["className", "color", "value", "valueBuffer", "variant"]); const styleProps = _extends({}, props, { color, variant }); const classes = useUtilityClasses(styleProps); const theme = useTheme(); const rootProps = {}; const inlineStyles = { bar1: {}, bar2: {} }; if (variant === 'determinate' || variant === 'buffer') { if (value !== undefined) { rootProps['aria-valuenow'] = Math.round(value); rootProps['aria-valuemin'] = 0; rootProps['aria-valuemax'] = 100; let transform = value - 100; if (theme.direction === 'rtl') { transform = -transform; } inlineStyles.bar1.transform = `translateX(${transform}%)`; } else if (process.env.NODE_ENV !== 'production') { console.error('Material-UI: You need to provide a value prop ' + 'when using the determinate or buffer variant of LinearProgress .'); } } if (variant === 'buffer') { if (valueBuffer !== undefined) { let transform = (valueBuffer || 0) - 100; if (theme.direction === 'rtl') { transform = -transform; } inlineStyles.bar2.transform = `translateX(${transform}%)`; } else if (process.env.NODE_ENV !== 'production') { console.error('Material-UI: You need to provide a valueBuffer prop ' + 'when using the buffer variant of LinearProgress.'); } } return /*#__PURE__*/_jsxs(LinearProgressRoot, _extends({ className: clsx(classes.root, className), styleProps: styleProps, role: "progressbar" }, rootProps, { ref: ref }, other, { children: [variant === 'buffer' ? /*#__PURE__*/_jsx(LinearProgressDashed, { className: classes.dashed, styleProps: styleProps }) : null, /*#__PURE__*/_jsx(LinearProgressBar1, { className: classes.bar1, styleProps: styleProps, style: inlineStyles.bar1 }), variant === 'determinate' ? null : /*#__PURE__*/_jsx(LinearProgressBar2, { className: classes.bar2, styleProps: styleProps, style: inlineStyles.bar2 })] })); }); process.env.NODE_ENV !== "production" ? LinearProgress.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. * @default 'primary' */ color: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['primary', 'secondary']), PropTypes.string]), /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * The value of the progress indicator for the determinate and buffer variants. * Value between 0 and 100. */ value: PropTypes.number, /** * The value for the buffer variant. * Value between 0 and 100. */ valueBuffer: PropTypes.number, /** * The variant to use. * Use indeterminate or query when there is no progress value. * @default 'indeterminate' */ variant: PropTypes.oneOf(['buffer', 'determinate', 'indeterminate', 'query']) } : void 0; export default LinearProgress;
/* * * * (c) 2010-2019 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from './Globals.js'; /** * Optional parameters for the tick. * @private * @interface Highcharts.TickParametersObject */ /** * Set category for the tick. * @name Highcharts.TickParametersObject#category * @type {string|undefined} */ /** * @name Highcharts.TickParametersObject#options * @type {Highcharts.Dictionary<any>|undefined} */ /** * Set tickmarkOffset for the tick. * @name Highcharts.TickParametersObject#tickmarkOffset * @type {number|undefined} */ import U from './Utilities.js'; var defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, extend = U.extend, isNumber = U.isNumber, pick = U.pick; var correctFloat = H.correctFloat, fireEvent = H.fireEvent, merge = H.merge, deg2rad = H.deg2rad; /* eslint-disable no-invalid-this, valid-jsdoc */ /** * The Tick class. * * @class * @name Highcharts.Tick * * @param {Highcharts.Axis} axis * The axis of the tick. * * @param {number} pos * The position of the tick on the axis in terms of axis values. * * @param {string} [type] * The type of tick, either 'minor' or an empty string * * @param {boolean} [noLabel=false] * Whether to disable the label or not. Defaults to false. * * @param {object} [parameters] * Optional parameters for the tick. */ H.Tick = function (axis, pos, type, noLabel, parameters) { /** * The related axis of the tick. * @name Highcharts.Tick#axis * @type {Highcharts.Axis} */ this.axis = axis; /** * The logical position of the tick on the axis in terms of axis values. * @name Highcharts.Tick#pos * @type {number} */ this.pos = pos; /** * The tick type, which can be `"minor"`, or an empty string. * @name Highcharts.Tick#type * @type {string} */ this.type = type || ''; this.isNew = true; this.isNewLabel = true; this.parameters = parameters || {}; /** * The mark offset of the tick on the axis. Usually `undefined`, numeric for * grid axes. * @name Highcharts.Tick#tickmarkOffset * @type {number|undefined} */ this.tickmarkOffset = this.parameters.tickmarkOffset; this.options = this.parameters.options; if (!type && !noLabel) { this.addLabel(); } }; /** @lends Highcharts.Tick.prototype */ H.Tick.prototype = { /** * Write the tick label. * * @private * @function Highcharts.Tick#addLabel * @return {void} */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = pick(tick.options && tick.options.labels, options.labels), str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = this.parameters.category || (categories ? pick(categories[pos], names[pos], pos) : pos), label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat, dateTimeLabelFormats, i, list; // Set the datetime label format. If a higher rank is set for this // position, use that. If not, use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormats = chart.time.resolveDTLFormat(options.dateTimeLabelFormats[(!options.grid && tickPositionInfo.higherRanks[pos]) || tickPositionInfo.unitName]); dateTimeLabelFormat = dateTimeLabelFormats.main; } // set properties for access in render method /** * True if the tick is the first one on the axis. * @name Highcharts.Tick#isFirst * @readonly * @type {boolean|undefined} */ tick.isFirst = isFirst; /** * True if the tick is the last one on the axis. * @name Highcharts.Tick#isLast * @readonly * @type {boolean|undefined} */ tick.isLast = isLast; // Get the string tick.formatCtx = { axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, tickPositionInfo: tickPositionInfo, value: axis.isLog ? correctFloat(axis.lin2log(value)) : value, pos: pos }; str = axis.labelFormatter.call(tick.formatCtx, this.formatCtx); // Set up conditional formatting based on the format list if existing. list = dateTimeLabelFormats && dateTimeLabelFormats.list; if (list) { tick.shortenLabel = function () { for (i = 0; i < list.length; i++) { label.attr({ text: axis.labelFormatter.call(extend(tick.formatCtx, { dateTimeLabelFormat: list[i] })) }); if (label.getBBox().width < axis.getSlotWidth(tick) - 2 * pick(labelOptions.padding, 5)) { return; } } label.attr({ text: '' }); }; } // first call if (!defined(label)) { /** * The rendered label of the tick. * @name Highcharts.Tick#label * @type {Highcharts.SVGElement|undefined} */ tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer .text(str, 0, 0, labelOptions.useHTML) .add(axis.labelGroup) : null; // Un-rotated length if (label) { // Without position absolute, IE export sometimes is wrong if (!chart.styledMode) { label.css(merge(labelOptions.style)); } label.textPxLength = label.getBBox().width; } // Base value to detect change for new calls to getBBox tick.rotation = 0; // update } else if (label && label.textStr !== str) { // When resetting text, also reset the width if dynamically set // (#8809) if (label.textWidth && !(labelOptions.style && labelOptions.style.width) && !label.styles.width) { label.css({ width: null }); } label.attr({ text: str }); label.textPxLength = label.getBBox().width; } }, /** * Get the offset height or width of the label * * @private * @function Highcharts.Tick#getLabelSize * @return {number} */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right * edge, or hide them if they collide into the neighbour label. * * @private * @function Highcharts.Tick#handleOverflow * @param {Highcharts.PositionObject} xy * @return {void} */ handleOverflow: function (xy) { var tick = this, axis = this.axis, labelOptions = axis.options.labels, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, Math.max(!axis.isRadial ? axis.pos + axis.len : 0, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign || label.attr('align')], labelWidth = label.getBBox().width, slotWidth = axis.getSlotWidth(tick), modifiedSlotWidth = slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {}; // Check if the label overshoots the chart spacing box. If it does, move // it. If it now overshoots the slotWidth, add ellipsis. if (!rotation && pick(labelOptions.overflow, 'justify') === 'justify') { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor; goRight = -1; } modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177 if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') { xy.x += (goRight * (slotWidth - modifiedSlotWidth - xCorrection * (slotWidth - Math.min(labelWidth, modifiedSlotWidth)))); } // If the label width exceeds the available space, set a text width // to be picked up below. Also, if a width has been set before, we // need to set a new one because the reported labelWidth will be // limited by the box (#3938). if (labelWidth > modifiedSlotWidth || (axis.autoRotation && (label.styles || {}).width)) { textWidth = modifiedSlotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge // of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = Math.round(pxPos / Math.cos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = Math.round((chartWidth - pxPos) / Math.cos(rotation * deg2rad)); } if (textWidth) { if (tick.shortenLabel) { tick.shortenLabel(); } else { css.width = Math.floor(textWidth); if (!(labelOptions.style || {}).textOverflow) { css.textOverflow = 'ellipsis'; } label.css(css); } } }, /** * Gets the x and y positions for ticks in terms of pixels. * * @private * @function Highcharts.Tick#getPosition * * @param {boolean} horiz * Whether the tick is on an horizontal axis or not. * * @param {number} tickPos * Position of the tick. * * @param {number} tickmarkOffset * Tickmark offset for all ticks. * * @param {boolean} [old] * Whether the axis has changed or not. * * @return {Highcharts.PositionObject} * The tick position. * * @fires Highcharts.Tick#event:afterGetPosition */ getPosition: function (horiz, tickPos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, pos; pos = { x: horiz ? H.correctFloat(axis.translate(tickPos + tickmarkOffset, null, null, old) + axis.transB) : (axis.left + axis.offset + (axis.opposite ? (((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left) : 0)), y: horiz ? (cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0)) : H.correctFloat(cHeight - axis.translate(tickPos + tickmarkOffset, null, null, old) - axis.transB) }; // Chrome workaround for #10516 pos.y = Math.max(Math.min(pos.y, 1e5), -1e5); fireEvent(this, 'afterGetPosition', { pos: pos }); return pos; }, /** * Get the x, y position of the tick label * * @private * @return {Highcharts.PositionObject} */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = ( // #7911 axis.isLinked && axis.linkedParent ? axis.linkedParent.reversed : axis.reversed), staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = labelOptions.y, // Adjust for label alignment if we use reserveSpace: true (#5286) labelOffsetCorrection = (!horiz && !axis.reserveSpaceDefault ? -axis.labelOffset * (axis.labelAlign === 'center' ? 0.5 : 1) : 0), line, pos = {}; if (!defined(yOffset)) { if (axis.side === 0) { yOffset = label.rotation ? -8 : -label.getBBox().height; } else if (axis.side === 2) { yOffset = rotCorr.y + 8; } else { // #3140, #3140 yOffset = Math.cos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2); } } x = x + labelOptions.x + labelOffsetCorrection + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); if (axis.opposite) { line = staggerLines - line - 1; } y += line * (axis.labelOffset / staggerLines); } pos.x = x; pos.y = Math.round(y); fireEvent(this, 'afterGetLabelPosition', { pos: pos, tickmarkOffset: tickmarkOffset, index: index }); return pos; }, /** * Extendible method to return the path of the marker * * @private * */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ 'M', x, y, 'L', x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Renders the gridLine. * * @private * @param {boolean} old Whether or not the tick is old * @param {number} opacity The opacity of the grid line * @param {number} reverseCrisp Modifier for avoiding overlapping 1 or -1 * @return {void} */ renderGridLine: function (old, opacity, reverseCrisp) { var tick = this, axis = tick.axis, options = axis.options, gridLine = tick.gridLine, gridLinePath, attribs = {}, pos = tick.pos, type = tick.type, tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset), renderer = axis.chart.renderer, gridPrefix = type ? type + 'Grid' : 'grid', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle']; if (!gridLine) { if (!axis.chart.styledMode) { attribs.stroke = gridLineColor; attribs['stroke-width'] = gridLineWidth; if (dashStyle) { attribs.dashstyle = dashStyle; } } if (!type) { attribs.zIndex = 1; } if (old) { opacity = 0; } /** * The rendered grid line of the tick. * @name Highcharts.Tick#gridLine * @type {Highcharts.SVGElement|undefined} */ tick.gridLine = gridLine = renderer.path() .attr(attribs) .addClass('highcharts-' + (type ? type + '-' : '') + 'grid-line') .add(axis.gridGroup); } if (gridLine) { gridLinePath = axis.getPlotLinePath({ value: pos + tickmarkOffset, lineWidth: gridLine.strokeWidth() * reverseCrisp, force: 'pass', old: old }); // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (gridLinePath) { gridLine[old || tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } }, /** * Renders the tick mark. * * @private * @param {Highcharts.PositionObject} xy The position vector of the mark * @param {number} opacity The opacity of the mark * @param {number} reverseCrisp Modifier for avoiding overlapping 1 or -1 * @return {void} */ renderMark: function (xy, opacity, reverseCrisp) { var tick = this, axis = tick.axis, options = axis.options, renderer = axis.chart.renderer, type = tick.type, tickPrefix = type ? type + 'Tick' : 'tick', tickSize = axis.tickSize(tickPrefix), mark = tick.mark, isNewMark = !mark, x = xy.x, y = xy.y, tickWidth = pick(options[tickPrefix + 'Width'], !type && axis.isXAxis ? 1 : 0), // X axis defaults to 1 tickColor = options[tickPrefix + 'Color']; if (tickSize) { // negate the length if (axis.opposite) { tickSize[0] = -tickSize[0]; } // First time, create it if (isNewMark) { /** * The rendered mark of the tick. * @name Highcharts.Tick#mark * @type {Highcharts.SVGElement|undefined} */ tick.mark = mark = renderer.path() .addClass('highcharts-' + (type ? type + '-' : '') + 'tick') .add(axis.axisGroup); if (!axis.chart.styledMode) { mark.attr({ stroke: tickColor, 'stroke-width': tickWidth }); } } mark[isNewMark ? 'attr' : 'animate']({ d: tick.getMarkPath(x, y, tickSize[0], mark.strokeWidth() * reverseCrisp, axis.horiz, renderer), opacity: opacity }); } }, /** * Renders the tick label. * Note: The label should already be created in init(), so it should only * have to be moved into place. * * @private * @param {Highcharts.PositionObject} xy The position vector of the label * @param {boolean} old Whether or not the tick is old * @param {number} opacity The opacity of the label * @param {number} index The index of the tick * @return {void} */ renderLabel: function (xy, old, opacity, index) { var tick = this, axis = tick.axis, horiz = axis.horiz, options = axis.options, label = tick.label, labelOptions = options.labels, step = labelOptions.step, tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset), show = true, x = xy.x, y = xy.y; if (label && isNumber(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and // last, it is a single centered tick, in which case we show the // label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && isNumber(xy.y)) { xy.opacity = opacity; label[tick.isNewLabel ? 'attr' : 'animate'](xy); tick.isNewLabel = false; } else { label.attr('y', -9999); // #1338 tick.isNewLabel = true; } } }, /** * Put everything in place * * @private * @param {number} index * @param {boolean} [old] * Use old coordinates to prepare an animation into new position * @param {number} [opacity] * @return {voids} */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, horiz = axis.horiz, pos = tick.pos, tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset), xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // Create the grid line this.renderGridLine(old, opacity, reverseCrisp); // create the tick mark this.renderMark(xy, opacity, reverseCrisp); // the label is created on init - now move it into place this.renderLabel(xy, old, opacity, index); tick.isNew = false; H.fireEvent(this, 'afterRender'); }, /** * Destructor for the tick prototype * * @private * @function Highcharts.Tick#destroy * @return {void} */ destroy: function () { destroyObjectProperties(this, this.axis); } };
var comb = require("comb"), define = comb.define; define({ /**@ignore*/ instance: { __providesAccurateRowsMatched: true, __requiresSqlStandardDateTimes: false, __supportsCte: true, __supportsDistinctOn: false, __supportsIntersectExcept: true, __supportsIntersectExceptAll: true, __supportsIsTrue: true, __supportsJoinUsing: true, __supportsModifyingJoins: false, __supportsMultipleColumnIn: true, __supportsTimestampTimezones: false, __supportsTimestampUsecs: true, __supportsWindowFunctions: false, /**@ignore*/ getters: { /**@lends patio.Dataset.prototype*/ // Whether this dataset quotes identifiers. /**@ignore*/ quoteIdentifiers: function () { return this.__quoteIdentifiers; }, // Whether this dataset will provide accurate number of rows matched for // delete and update statements. Accurate in this case is the number of // rows matched by the dataset's filter. /**@ignore*/ providesAccurateRowsMatched: function () { return this.__providesAccurateRowsMatched; }, //Whether the dataset requires SQL standard datetimes (false by default, // as most allow strings with ISO 8601 format). /**@ignore*/ requiresSqlStandardDateTimes: function () { return this.__requiresSqlStandardDateTimes; }, // Whether the dataset supports common table expressions (the WITH clause). /**@ignore*/ supportsCte: function () { return this.__supportsCte; }, // Whether the dataset supports the DISTINCT ON clause, false by default. /**@ignore*/ supportsDistinctOn: function () { return this.__supportsDistinctOn; }, //Whether the dataset supports the INTERSECT and EXCEPT compound operations, true by default. /**@ignore*/ supportsIntersectExcept: function () { return this.__supportsIntersectExcept; }, //Whether the dataset supports the INTERSECT ALL and EXCEPT ALL compound operations, true by default. /**@ignore*/ supportsIntersectExceptAll: function () { return this.__supportsIntersectExceptAll; }, //Whether the dataset supports the IS TRUE syntax. /**@ignore*/ supportsIsTrue: function () { return this.__supportsIsTrue; }, //Whether the dataset supports the JOIN table USING (column1, ...) syntax. /**@ignore*/ supportsJoinUsing: function () { return this.__supportsJoinUsing; }, //Whether modifying joined datasets is supported. /**@ignore*/ supportsModifyingJoins: function () { return this.__supportsModifyingJoins; }, //Whether the IN/NOT IN operators support multiple columns when an /**@ignore*/ supportsMultipleColumnIn: function () { return this.__supportsMultipleColumnIn; }, //Whether the dataset supports timezones in literal timestamps /**@ignore*/ supportsTimestampTimezones: function () { return this.__supportsTimestampTimezones; }, //Whether the dataset supports fractional seconds in literal timestamps /**@ignore*/ supportsTimestampUsecs: function () { return this.__supportsTimestampUsecs; }, //Whether the dataset supports window functions. /**@ignore*/ supportsWindowFunctions: function () { return this.__supportsWindowFunctions; } }, /**@ignore*/ setters: { /**@lends patio.Dataset.prototype*/ // Whether this dataset quotes identifiers. /**@ignore*/ quoteIdentifiers: function (val) { this.__quoteIdentifiers = val; }, // Whether this dataset will provide accurate number of rows matched for // delete and update statements. Accurate in this case is the number of // rows matched by the dataset's filter. /**@ignore*/ providesAccurateRowsMatched: function (val) { this.__providesAccurateRowsMatched = val; }, //Whether the dataset requires SQL standard datetimes (false by default, // as most allow strings with ISO 8601 format). /**@ignore*/ requiresSqlStandardDateTimes: function (val) { this.__requiresSqlStandardDateTimes = val; }, // Whether the dataset supports common table expressions (the WITH clause). /**@ignore*/ supportsCte: function (val) { this.__supportsCte = val; }, // Whether the dataset supports the DISTINCT ON clause, false by default. /**@ignore*/ supportsDistinctOn: function (val) { this.__supportsDistinctOn = val; }, //Whether the dataset supports the INTERSECT and EXCEPT compound operations, true by default. /**@ignore*/ supportsIntersectExcept: function (val) { this.__supportsIntersectExcept = val; }, //Whether the dataset supports the INTERSECT ALL and EXCEPT ALL compound operations, true by default. /**@ignore*/ supportsIntersectExceptAll: function (val) { this.__supportsIntersectExceptAll = val; }, //Whether the dataset supports the IS TRUE syntax. /**@ignore*/ supportsIsTrue: function (val) { this.__supportsIsTrue = val; }, //Whether the dataset supports the JOIN table USING (column1, ...) syntax. /**@ignore*/ supportsJoinUsing: function (val) { this.__supportsJoinUsing = val; }, //Whether modifying joined datasets is supported. /**@ignore*/ supportsModifyingJoins: function (val) { this.__supportsModifyingJoins = val; }, //Whether the IN/NOT IN operators support multiple columns when an /**@ignore*/ supportsMultipleColumnIn: function (val) { this.__supportsMultipleColumnIn = val; }, //Whether the dataset supports timezones in literal timestamps /**@ignore*/ supportsTimestampTimezones: function (val) { this.__supportsTimestampTimezones = val; }, //Whether the dataset supports fractional seconds in literal timestamps /**@ignore*/ supportsTimestampUsecs: function (val) { this.__supportsTimestampUsecs = val; }, //Whether the dataset supports window functions. /**@ignore*/ supportsWindowFunctions: function (val) { this.__supportsWindowFunctions = val; } } }, static: { /**@lends patio.Dataset*/ /** * @property {String[]} * @default ["quoteIdentifiers","providesAccurateRowsMatched","requiresSqlStandardDateTimes","supportsCte", * "supportsDistinctOn","supportsIntersectExcept","supportsIntersectExceptAll","supportsIsTrue","supportsJoinUsing", * "supportsModifyingJoins","supportsMultipleColumnIn","supportsTimestampTimezones","supportsTimestampUsecs", * "supportsWindowFunctions"] * Array of features. */ FEATURES: ["quoteIdentifiers", "providesAccurateRowsMatched", "requiresSqlStandardDateTimes", "supportsCte", "supportsDistinctOn", "supportsIntersectExcept", "supportsIntersectExceptAll", "supportsIsTrue", "supportsJoinUsing", "supportsModifyingJoins", "supportsMultipleColumnIn", "supportsTimestampTimezones", "supportsTimestampUsecs", "supportsWindowFunctions"] } }).as(module);
const path = require('path') const projectPath = require('./projectPath') const fs = require('fs') module.exports = function(jsDest, dest, filename) { filename = filename || 'rev-manifest.json' return function() { this.plugin("done", function(statsObject) { const stats = statsObject.toJson() const chunks = stats.assetsByChunkName const manifest = {} for (let key in chunks) { const originalFilename = key + '.js' // https://github.com/vigetlabs/blendid/issues/232#issuecomment-171963233 const chunkName = typeof chunks[key] === 'string' ? chunks[key] : chunks[key][0] manifest[path.join(jsDest, originalFilename)] = path.join(jsDest, chunkName) } fs.writeFileSync( projectPath(dest, filename), JSON.stringify(manifest) ) }) } }
version https://git-lfs.github.com/spec/v1 oid sha256:e16a05bfaddd80f902a2718913a5fb03a5944d02dab40f9ad573f4ac51110827 size 6681
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.build_gh_pages = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf;
var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var url = require('url'); var util = require('util'); var _ = require('underscore'); var env = require('./env'); var paramChecker = require('./param-checker'); module.exports.createPluginMgr = function (pluginInfos, logger) { return new PluginMgr(pluginInfos, logger); }; /** * manager class for plugins * @class PluginMgr * @constructor * */ function PluginMgr(logger) { this.pluginModules = []; this.pluginInfos = []; this.logger = logger; EventEmitter.call(this); } util.inherits(PluginMgr, EventEmitter); PluginMgr.prototype.loadAllPlugins = function (pluginInfos) { for (var i in pluginInfos) { //doLoadPluginModule(this, pluginInfos[i].name, pluginInfos[i].ver, pluginInfos[i].p); this.pluginInfos.push({ name: pluginInfos[i].name, path: pluginInfos[i].p, version: pluginInfos[i].ver }); } }; function doLoadPluginModule(self, name, ver, path) { var pluginModule = require(path); if (!pluginModule.name ) { throw new Error('plugin ' + path + ' miss required field name'); } if (!pluginModule.createSDK ) { throw new Error('plugin ' + path + ' miss required function create'); } if (!pluginModule.cfgDesc ) { throw new Error('plugin ' + path + ' miss required function cfgDesc'); } var checker = paramChecker.createChecker(pluginModule.cfgDesc); var pluginModuleInfo = { name: pluginModule.name, m: pluginModule, path: path, version: ver, plugin: pluginModule.createSDK(self.logger, checker, env.debug) }; self.pluginModules.push(pluginModuleInfo); self.logger.info({name: pluginModuleInfo.name}, 'load plugin module'); return pluginModuleInfo; }
myPager.addTask('config', { init: function (pageId, pageContent, event, dom, scope) { return function () { var form = new cForm('configForm'); var xmlDoc = helper.configParse(true); helper.configFieldsUi('editor.config.ui', xmlDoc, false, { change: function () { form.validate({required: 'invalide'}); }, saved: function (xmlStr) { //console.log('done'); } }); myTaskHelper.editorSwitchTab(event.target); } } });
/*globals Markdown */ define([ "jquery", "underscore", "utils", "logger", "classes/Extension", "text!html/markdownExtraSettingsBlock.html", 'google-code-prettify', 'highlightjs', 'crel', 'pagedownExtra' ], function($, _, utils, logger, Extension, markdownExtraSettingsBlockHTML, prettify, hljs) { var markdownExtra = new Extension("markdownExtra", "Markdown Extra", true); markdownExtra.settingsBlock = markdownExtraSettingsBlockHTML; markdownExtra.defaultConfig = { extensions: [ "fenced_code_gfm", "tables", "def_list", "attr_list", "footnotes", "smartypants", "strikethrough", "newlines" ], intraword: true, comments: true, highlighter: "highlight" }; markdownExtra.onLoadSettings = function() { function hasExtension(extensionName) { return _.some(markdownExtra.config.extensions, function(extension) { return extension == extensionName; }); } utils.setInputChecked("#input-markdownextra-fencedcodegfm", hasExtension("fenced_code_gfm")); utils.setInputChecked("#input-markdownextra-tables", hasExtension("tables")); utils.setInputChecked("#input-markdownextra-deflist", hasExtension("def_list")); utils.setInputChecked("#input-markdownextra-attrlist", hasExtension("attr_list")); utils.setInputChecked("#input-markdownextra-footnotes", hasExtension("footnotes")); utils.setInputChecked("#input-markdownextra-smartypants", hasExtension("smartypants")); utils.setInputChecked("#input-markdownextra-strikethrough", hasExtension("strikethrough")); utils.setInputChecked("#input-markdownextra-newlines", hasExtension("newlines")); utils.setInputChecked("#input-markdownextra-intraword", markdownExtra.config.intraword); utils.setInputChecked("#input-markdownextra-comments", markdownExtra.config.comments); utils.setInputValue("#input-markdownextra-highlighter", markdownExtra.config.highlighter); }; markdownExtra.onSaveSettings = function(newConfig) { newConfig.extensions = []; utils.getInputChecked("#input-markdownextra-fencedcodegfm") && newConfig.extensions.push("fenced_code_gfm"); utils.getInputChecked("#input-markdownextra-tables") && newConfig.extensions.push("tables"); utils.getInputChecked("#input-markdownextra-deflist") && newConfig.extensions.push("def_list"); utils.getInputChecked("#input-markdownextra-attrlist") && newConfig.extensions.push("attr_list"); utils.getInputChecked("#input-markdownextra-footnotes") && newConfig.extensions.push("footnotes"); utils.getInputChecked("#input-markdownextra-smartypants") && newConfig.extensions.push("smartypants"); utils.getInputChecked("#input-markdownextra-strikethrough") && newConfig.extensions.push("strikethrough"); utils.getInputChecked("#input-markdownextra-newlines") && newConfig.extensions.push("newlines"); newConfig.intraword = utils.getInputChecked("#input-markdownextra-intraword"); newConfig.comments = utils.getInputChecked("#input-markdownextra-comments"); newConfig.highlighter = utils.getInputValue("#input-markdownextra-highlighter"); }; var eventMgr; markdownExtra.onEventMgrCreated = function(eventMgrParameter) { eventMgr = eventMgrParameter; }; var previewContentsElt; markdownExtra.onReady = function() { previewContentsElt = document.getElementById('preview-contents'); }; markdownExtra.onPagedownConfigure = function(editor) { var converter = editor.getConverter(); var extraOptions = { extensions: markdownExtra.config.extensions, highlighter: "prettify" }; if(markdownExtra.config.intraword === true) { var converterOptions = { _DoItalicsAndBold: function(text) { text = text.replace(/([^\w*]|^)(\*\*|__)(?=\S)(.+?[*_]*)(?=\S)\2(?=[^\w*]|$)/g, "$1<strong>$3</strong>"); text = text.replace(/([^\w*]|^)(\*|_)(?=\S)(.+?)(?=\S)\2(?=[^\w*]|$)/g, "$1<em>$3</em>"); // Redo bold to handle _**word**_ text = text.replace(/([^\w*]|^)(\*\*|__)(?=\S)(.+?[*_]*)(?=\S)\2(?=[^\w*]|$)/g, "$1<strong>$3</strong>"); return text; } }; converter.setOptions(converterOptions); } if(markdownExtra.config.comments === true) { converter.hooks.chain("postConversion", function(text) { return text.replace(/<!--.*?-->/g, function(wholeMatch) { return wholeMatch.replace(/^<!---(.+?)-?-->$/, ' <span class="comment label label-danger">$1</span> '); }); }); } if(markdownExtra.config.highlighter == "highlight") { var previewContentsElt = document.getElementById('preview-contents'); editor.hooks.chain("onPreviewRefresh", function() { _.each(previewContentsElt.querySelectorAll('.prettyprint > code'), function(elt) { !elt.highlighted && hljs.highlightBlock(elt); elt.highlighted = true; }); }); } else if(markdownExtra.config.highlighter == "prettify") { editor.hooks.chain("onPreviewRefresh", prettify.prettyPrint); } Markdown.Extra.init(converter, extraOptions); }; return markdownExtra; });
'use strict'; module.exports = { app: { title: 'MEAN.JS', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'mongodb, express, angularjs, node.js, mongoose, passport', googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID' }, port: process.env.PORT || 3000, templateEngine: 'swig', // Session details // session expiration is set by default to 24 hours sessionExpiration: 24 * (60 * 60 * 1000), // sessionSecret should be changed for security measures and concerns sessionSecret: 'MEAN', // sessionKey is set to the generic sessionId key used by PHP applications // for obsecurity reasons sessionKey: 'sessionId', sessionCollection: 'sessions', logo: 'modules/core/img/brand/logo.png', favicon: 'modules/core/img/brand/favicon.ico' };
/* Adapted for Node.js by Matt Robenolt Reference: http://www.tumuski.com/2010/04/nibbler/ */ /** * Node.js example: * * var nibbler = require('nibbler'); * * nibbler.b32encode('Hello, World!'); // returns JBSWY3DPFQQFO33SNRSCC=====' * nibbler.b32decode('JBSWY3DPFQQFO33SNRSCC====='); // returns 'Hello, World!' * nibbler.b64encode('Hello, World!'); // returns 'SGVsbG8sIFdvcmxkIQ==' * nibbler.b64decode('SGVsbG8sIFdvcmxkIQ=='); // returns 'Hello, World!' */ /* Copyright (c) 2010 Thomas Peri http://www.tumuski.com/ 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. */ /*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, regexp: true, newcap: true, immed: true */ // (good parts minus bitwise and strict, plus white.) /** * Nibbler - Multi-Base Encoder * * version 2010-04-07 * * Options: * dataBits: The number of bits in each character of unencoded data. * codeBits: The number of bits in each character of encoded data. * keyString: The characters that correspond to each value when encoded. * pad (optional): The character to pad the end of encoded output. * arrayData (optional): If truthy, unencoded data is an array instead of a string. * * Example: * * var base64_8bit = new Nibbler({ * dataBits: 8, * codeBits: 6, * keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', * pad: '=' * }); * base64_8bit.encode("Hello, World!"); // returns "SGVsbG8sIFdvcmxkIQ==" * base64_8bit.decode("SGVsbG8sIFdvcmxkIQ=="); // returns "Hello, World!" * * var base64_7bit = new Nibbler({ * dataBits: 7, * codeBits: 6, * keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', * pad: '=' * }); * base64_7bit.encode("Hello, World!"); // returns "kZdmzesQV9/LZkQg==" * base64_7bit.decode("kZdmzesQV9/LZkQg=="); // returns "Hello, World!" * */ var Nibbler = function (options) { var construct, // options pad, dataBits, codeBits, keyString, arrayData, // private instance variables mask, group, max, // private methods gcd, translate, // public methods encode, decode; // pseudo-constructor construct = function () { var i, mag, prev; // options pad = options.pad || ''; dataBits = options.dataBits; codeBits = options.codeBits; keyString = options.keyString; arrayData = options.arrayData; // bitmasks mag = Math.max(dataBits, codeBits); prev = 0; mask = []; for (i = 0; i < mag; i += 1) { mask.push(prev); prev += prev + 1; } max = prev; // ouput code characters in multiples of this number group = dataBits / gcd(dataBits, codeBits); }; // greatest common divisor gcd = function (a, b) { var t; while (b !== 0) { t = b; b = a % b; a = t; } return a; }; // the re-coder translate = function (input, bitsIn, bitsOut, decoding) { var i, len, chr, byteIn, buffer, size, output, write; // append a byte to the output write = function (n) { if (!decoding) { output.push(keyString.charAt(n)); } else if (arrayData) { output.push(n); } else { output.push(String.fromCharCode(n)); } }; buffer = 0; size = 0; output = []; len = input.length; for (i = 0; i < len; i += 1) { // the new size the buffer will be after adding these bits size += bitsIn; // read a character if (decoding) { // decode it chr = input.charAt(i); byteIn = keyString.indexOf(chr); if (chr === pad) { break; } else if (byteIn < 0) { throw 'the character "' + chr + '" is not a member of ' + keyString; } } else { if (arrayData) { byteIn = input[i]; } else { byteIn = input.charCodeAt(i); } if ((byteIn | max) !== max) { throw byteIn + " is outside the range 0-" + max; } } // shift the buffer to the left and add the new bits buffer = (buffer << bitsIn) | byteIn; // as long as there's enough in the buffer for another output... while (size >= bitsOut) { // the new size the buffer will be after an output size -= bitsOut; // output the part that lies to the left of that number of bits // by shifting the them to the right write(buffer >> size); // remove the bits we wrote from the buffer // by applying a mask with the new size buffer &= mask[size]; } } // If we're encoding and there's input left over, pad the output. // Otherwise, leave the extra bits off, 'cause they themselves are padding if (!decoding && size > 0) { // flush the buffer write(buffer << (bitsOut - size)); // add padding keyString for the remainder of the group len = output.length % group; for (i = 0; i < len; i += 1) { output.push(pad); } } // string! return (arrayData && decoding) ? output : output.join(''); }; /** * Encode. Input and output are strings. */ encode = function (input) { return translate(input, dataBits, codeBits, false); }; /** * Decode. Input and output are strings. */ decode = function (input) { return translate(input, codeBits, dataBits, true); }; this.encode = encode; this.decode = decode; construct(); }; var Base32 = new Nibbler({ dataBits: 8, codeBits: 5, keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', pad: '=' }); var Base64 = new Nibbler({ dataBits: 8, codeBits: 6, keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', pad: '=' }); exports.Nibbler = Nibbler; exports.b32encode = Base32.encode; exports.b32decode = Base32.decode; exports.b64encode = Base64.encode; exports.b64decode = Base64.decode;
(function () { 'use strict'; angular .module('doleticApp') .component('uaDisabledTableComponent', uaDisabledTableComponent()); function uaDisabledTableComponent() { return { bindings: {}, controller: "uaDisabledTableController", templateUrl: "app/components/ua/disabledTab/disabled-table/disabled-table.template.html" } } })();
/** * Class that manages making request, called by all of the API methods. * @type {[type]} */ module.exports = Transport; var _ = require('./utils'); var errors = require('./errors'); var Host = require('./host'); var Promise = require('promise-js'); var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault'); var findCommonProtocol = require('./transport/find_common_protocol'); function Transport(config) { var self = this; config = self._config = config || {}; var LogClass = (typeof config.log === 'function') ? config.log : require('./log'); config.log = self.log = new LogClass(config); // setup the connection pool var ConnectionPool = _.funcEnum(config, 'connectionPool', Transport.connectionPools, 'main'); self.connectionPool = new ConnectionPool(config); // setup the serializer var Serializer = _.funcEnum(config, 'serializer', Transport.serializers, 'json'); self.serializer = new Serializer(config); // setup the nodesToHostCallback self.nodesToHostCallback = _.funcEnum(config, 'nodesToHostCallback', Transport.nodesToHostCallbacks, 'main'); // setup max retries self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3; // setup endpoint to use for sniffing self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint') ? config.sniffEndpoint : '/_nodes/_all/clear'; // setup requestTimeout default self.requestTimeout = config.hasOwnProperty('requestTimeout') ? config.requestTimeout : 30000; if (config.hasOwnProperty('defer')) { self.defer = config.defer; } // randomizeHosts option var randomizeHosts = config.hasOwnProperty('randomizeHosts') ? !!config.randomizeHosts : true; if (config.host) { config.hosts = config.host; } if (config.hosts) { var hostsConfig = _.createArray(config.hosts, function (val) { if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) { return val; } }); if (!hostsConfig) { throw new TypeError('Invalid hosts config. Expected a URL, an array of urls, a host config object, ' + 'or an array of host config objects.'); } var hosts = _.map(hostsConfig, function (conf) { return (conf instanceof Host) ? conf : new Host(conf, self._config); }); if (randomizeHosts) { hosts = _.shuffle(hosts); } self.connectionPool.setHosts(hosts); } if (config.hasOwnProperty('sniffedNodesProtocol')) { self.sniffedNodesProtocol = config.sniffedNodesProtocol || null; } else { self.sniffedNodesProtocol = findCommonProtocol(self.connectionPool.getAllHosts()) || null; } if (config.sniffOnStart) { self.sniff(); } if (config.sniffInterval) { self._timeout(function doSniff() { self.sniff(); self._timeout(doSniff, config.sniffInterval); }, config.sniffInterval); } if (config.sniffOnConnectionFault) { patchSniffOnConnectionFault(self); } } Transport.connectionPools = { main: require('./connection_pool') }; Transport.serializers = require('./serializers'); Transport.nodesToHostCallbacks = { main: require('./nodes_to_host') }; Transport.prototype.defer = function () { var defer = {}; defer.promise = new Promise(function (resolve, reject) { defer.resolve = resolve; defer.reject = reject; }); return defer; }; /** * Perform a request with the client's transport * * @method request * @todo async body writing * @todo abort * @todo access to custom headers, modifying of request in general * @param {object} params * @param {Number} params.requestTimeout - timeout for the entire request (inculding all retries) * @param {Number} params.maxRetries - number of times the request will be re-run in * the original node chosen can not be connected to. * @param {String} params.url - The url for the request * @param {String} params.method - The HTTP method for the request * @param {String} params.body - The body of the HTTP request * @param {Function} cb - A function to call back with (error, responseBody, responseStatus) */ Transport.prototype.request = function (params, cb) { var self = this; var remainingRetries = this.maxRetries; var requestTimeout = this.requestTimeout; var connection; // set in sendReqWithConnection var aborted = false; // several connector will respond with an error when the request is aborted var requestAborter; // an abort function, returned by connection#request() var requestTimeoutId; // the id of the ^timeout var ret; // the object returned to the user, might be a promise var defer; // the defer object, will be set when we are using promises. var body = params.body; var headers = !params.headers ? {} : _.transform(params.headers, function (headers, val, name) { headers[String(name).toLowerCase()] = val; }); self.log.debug('starting request', params); // determine the response based on the presense of a callback if (typeof cb === 'function') { // handle callbacks within a domain if (process.domain) { cb = process.domain.bind(cb); } ret = { abort: abortRequest }; } else { defer = this.defer(); ret = defer.promise; ret.abort = abortRequest; } if (body && params.method === 'GET') { _.nextTick(respond, new TypeError('Body can not be sent with method "GET"')); return ret; } // serialize the body if (body) { var serializer = self.serializer; var serializeFn = serializer[params.bulkBody ? 'bulkBody' : 'serialize']; body = serializeFn.call(serializer, body); if (!headers['content-type']) { headers['content-type'] = serializeFn.contentType; } } if (params.hasOwnProperty('maxRetries')) { remainingRetries = params.maxRetries; } if (params.hasOwnProperty('requestTimeout')) { requestTimeout = params.requestTimeout; } params.req = { method: params.method, path: params.path || '/', query: params.query, body: body, headers: headers }; function sendReqWithConnection(err, _connection) { if (aborted) { return; } if (err) { respond(err); } else if (_connection) { connection = _connection; requestAborter = connection.request(params.req, checkRespForFailure); } else { self.log.warning('No living connections'); respond(new errors.NoConnections()); } } function checkRespForFailure(err, body, status, headers) { if (aborted) { return; } requestAborter = void 0; if (err instanceof errors.RequestTypeError) { self.log.error('Connection refused to execute the request', err); respond(err, body, status, headers); return; } if (err) { connection.setStatus('dead'); if (remainingRetries) { remainingRetries--; self.log.error('Request error, retrying' + (err.message ? ' -- ' + err.message : '')); self.connectionPool.select(sendReqWithConnection); } else { self.log.error('Request complete with error' + (err.message ? ' -- ' + err.message : '')); respond(new errors.ConnectionFault(err)); } } else { self.log.debug('Request complete'); respond(void 0, body, status, headers); } } function respond(err, body, status, headers) { if (aborted) { return; } self._timeout(requestTimeoutId); var parsedBody; var isJson = !headers || (headers['content-type'] && ~headers['content-type'].indexOf('application/json')); if (!err && body) { if (isJson) { parsedBody = self.serializer.deserialize(body); if (parsedBody == null) { err = new errors.Serialization(); parsedBody = body; } } else { parsedBody = body; } } // does the response represent an error? if ( (!err || err instanceof errors.Serialization) && (status < 200 || status >= 300) && (!params.ignore || !_.contains(params.ignore, status)) ) { var errorMetadata = _.pick(params.req, ['path', 'query', 'body']); errorMetadata.statusCode = status; errorMetadata.response = body; if (status === 401 && headers && headers['www-authenticate']) { errorMetadata.wwwAuthenticateDirective = headers['www-authenticate']; } if (errors[status]) { err = new errors[status](parsedBody && parsedBody.error, errorMetadata); } else { err = new errors.Generic('unknown error', errorMetadata); } } // can we cast notfound to false? if (params.castExists) { if (err && err instanceof errors.NotFound) { parsedBody = false; err = void 0; } else { parsedBody = !err; } } // how do we send the response? if (typeof cb === 'function') { if (err) { cb(err, parsedBody, status); } else { cb(void 0, parsedBody, status); } } else if (err) { err.body = parsedBody; err.status = status; defer.reject(err); } else { defer.resolve(parsedBody); } } function abortRequest() { if (aborted) { return; } aborted = true; remainingRetries = 0; self._timeout(requestTimeoutId); if (typeof requestAborter === 'function') { requestAborter(); } } if (requestTimeout && requestTimeout !== Infinity) { requestTimeoutId = this._timeout(function () { respond(new errors.RequestTimeout('Request Timeout after ' + requestTimeout + 'ms')); abortRequest(); }, requestTimeout); } if (connection) { sendReqWithConnection(void 0, connection); } else { self.connectionPool.select(sendReqWithConnection); } return ret; }; Transport.prototype._timeout = function (cb, delay) { if (this.closed) return; var id; var timers = this._timers || (this._timers = []); if ('function' !== typeof cb) { id = cb; cb = void 0; } if (cb) { // set the timer id = setTimeout(function () { _.pull(timers, id); cb(); }, delay); timers.push(id); return id; } if (id) { clearTimeout(id); var i = this._timers.indexOf(id); if (i !== -1) { this._timers.splice(i, 1); } } }; /** * Ask an ES node for a list of all the nodes, add/remove nodes from the connection * pool as appropriate * * @param {Function} cb - Function to call back once complete */ Transport.prototype.sniff = function (cb) { var connectionPool = this.connectionPool; var nodesToHostCallback = this.nodesToHostCallback; var log = this.log; var globalConfig = this._config; var sniffedNodesProtocol = this.sniffedNodesProtocol; // make cb a function if it isn't cb = typeof cb === 'function' ? cb : _.noop; this.request({ path: this.sniffEndpoint, method: 'GET' }, function (err, resp, status) { if (!err && resp && resp.nodes) { var hostsConfigs; try { hostsConfigs = nodesToHostCallback(resp.nodes); } catch (e) { log.error(new Error('Unable to convert node list from ' + this.sniffEndpoint + ' to hosts durring sniff. Encountered error:\n' + (e.stack || e.message))); return; } connectionPool.setHosts(_.map(hostsConfigs, function (hostConfig) { if (sniffedNodesProtocol) { hostConfig.protocol = sniffedNodesProtocol; } return new Host(hostConfig, globalConfig); })); } cb(err, resp, status); }); }; /** * Close the Transport, which closes the logs and connection pool * @return {[type]} [description] */ Transport.prototype.close = function () { this.log.close(); this.closed = true; _.each(this._timers, clearTimeout); this._timers = null; this.connectionPool.close(); };
E2.p = E2.plugins["atan2_modulator"] = function(core, node) { this.desc = 'Atan2(x, y).'; this.input_slots = [ { name: 'x value', dt: core.datatypes.FLOAT, desc: 'X value.', def: 0.0 }, { name: 'y value', dt: core.datatypes.FLOAT, desc: 'Y value.', def: 0.0 } ]; this.output_slots = [ { name: 'result', dt: core.datatypes.FLOAT, desc: 'atan(<b>x</b>,<b>y</b>).', def: 0.0 } ]; }; E2.p.prototype.reset = function() { this.x_value = 0.0; this.y_value = 0.0; }; E2.p.prototype.update_input = function(slot, data) { if (slot.index === 0) this.x_value = data; else this.y_value = data; }; E2.p.prototype.update_output = function(slot) { this.value = Math.atan2(this.x_value, this.y_value); return this.value; };
var h = require('virtual-dom/h') , inherits = require('util').inherits , BaseElement = require('./base-element') module.exports = Overview function Overview(target) { BaseElement.call(this, target) var self = this this.lefts = [ h('i.fa.fa-chevron-up', { onclick: function(e) { self.previousRecent() } }) , h('i.fa.fa-chevron-down', { onclick: function(e) { self.nextRecent() } }) , '' ] } inherits(Overview, BaseElement) var titles = { send: 'Sent Paycoin' , receive: 'Received Paycoin' , stake: 'Staked Paycoin' } Overview.prototype.previousRecent = function previousRecent() { var self = this var idx = self.target.data.recentTxIndex if (!idx) return false self.target.updateRecent(idx - 1, function(err) { self.target.emit('render') }) } Overview.prototype.nextRecent = function nextRecent() { var self = this var idx = self.target.data.recentTxIndex if (idx === self.target.data.transactions.length - 1) return false self.target.updateRecent(idx + 1, function(err) { self.target.emit('render') }) } Overview.prototype.txRow = function txRow(tx, idx) { var self = this if (!tx) { return h('tr', [ h('td.col-sm-1.text-3x.text-center', [ self.lefts[idx] ]) , h('td.col-sm-7') , h('td.col-sm-4') ]) } var left = self.lefts[idx] var title = titles[tx.category] var text = tx.category === 'stake' ? '' : `to ${tx.address}` return h('tr', [ h('td.col-sm-1.text-3x.text-center', [ left ]) , h('td.col-sm-7.text-white.text-lg', [ title , h('br') , h('small', { style: { fontSize: '11px' } }, [ text ]) ]) , txAmount(tx) ]) } function txAmount(tx) { var amount = +tx.amount var cl = amount < 0 ? '.text-white' : '.text-success' amount = amount.toFixed(2) return h('td.col-sm-4.text-lg.text-right${cl}', [ `${amount} XPY` , h('br') ]) } Overview.prototype.render = function(info, recentTxs) { var self = this var stake = (+info.stake || 0).toFixed(6) return [ h('#overview.h-full.flex-col', [ h('.col-sm-12.bg-primary.dk.flex-fill.flex-col', [ h('.row.flex-fill.flex-row', [ h('.col-sm-6.m-t-b-a', [ h('h2.m-none.text-white.font-thin', 'BALANCE') , h('h1.m-none.text-6x.font-thin.text-white', String(info.balance)) , h('p', String(info.unconfirmed) + ' unconfirmed') ]) , h('.col-sm-6.text-right.m-t-b-a', [ h('h3.m-none.text-white.font-thin', 'STAKING') , h('h1.m-none.text-3x.font-thin.text-white', stake) , h('h2.m-none.text-white.font-thin', ' currently staking') ]) ]) ]) , h('.col-sm-12.bg-dark.lter.flex-fill.flex-row.m-none.no-padder', [ h('.col-sm-6.flex-fill', [ h('h3.m-t-xl.m-b-none.text-white.font-thin', 'RECENT TRANSACTIONS') , h('.row', [ h('table.col-sm-12', [ h('tbody', [ self.txRow(recentTxs[0], 0) , self.txRow(recentTxs[1], 1) , self.txRow(recentTxs[2], 2) ]) ]) ]) ]) , h('.col-sm-6.text-right.bg-light.flex-fill.no-padder.flex-col#nav', [ h('a.btn.btn-default.w-full.no-radius.flex-fill.flex-col', { 'href': '#send' }, [ h('.inner.text-3x.font-thin.m-t-b-a', [ h('i.fa.fa-arrow-right.m-r-md') , 'SEND' ]) ]) , h('a.btn.btn-success.w-full.no-radius.flex-fill.flex-col', { 'href': '#receive' }, [ h('.inner.text-3x.font-thin.m-t-b-a', [ h('i.fa.fa-arrow-left.m-r-md') , 'RECEIVE' ]) ]) ]) ]) ]) ] }
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file ProjectModel.js * @author Arkadiy Paronyan arkadiy@ethdev.com * @date 2015 * Ethereum IDE client. */ var basicContractTemplate = "contract FirstContract {}" var htmlTemplate = "<!doctype>\n" + "<html>\n" + "<head>\n" + "<script type='text/javascript'>\n" + "\n" + "function get() {\n" + "\tvar param = document.getElementById('query').value;\n" + "\tvar res = contracts['Sample'].contract.get();\n" + "\tdocument.getElementById('queryres').innerText = res;\n" + "}\n" + "\n" + "function set() {\n" + "\tvar key = document.getElementById('key').value;\n" + "\tvar res = contracts['Sample'].contract.set(key);\n" + "}\n" + "\n" + "</script>\n" + "</head>\n" + "<body bgcolor='#E6E6FA'>\n" + "\t<h3>Sample Ratings</h3>\n" + "<div>\n" + "Store:\n" + "\t<input type='number' id='key'>\n" + "\t<button onclick='set()'>Save</button>\n" + "</div>\n" + "<div>\n" + "Query:\n" + "\t<input value='get' type='button' id='query' onclick='get()' />\n" + "\t<div id='queryres'></div>\n" + "</div>\n" + "</body>\n" + "</html>\n"; var contractTemplate = "//Sample contract\n" + "contract Sample\n" + "{\n" + "\tuint value;\n" + "\tfunction Sample(uint v) {\n" + "\t\tvalue = v;\n" + "\t}\n" + "\tfunction set(uint v) {\n" + "\t\tvalue = v;\n" + "\t}\n" + "\tfunction get() constant returns (uint) {\n" + "\t\treturn value;\n" + "\t}\n" + "}\n"; function saveDocument(doc) { documentSaving(doc); if (doc.isContract) contractSaved(doc); else documentSaved(doc); } function saveCurrentDocument() { saveDocument(currentDocument) } function saveDocuments(onlyContracts) { for (var i = 0; i < unsavedFiles.length; i++) { var d = unsavedFiles[i] if (!onlyContracts) saveDocument(d) else if (d.isContract) saveDocument(d) } } function saveAll() { saveDocuments(false) saveProject(); } function createProject() { newProjectDialog.open(); } function closeProject(callBack) { if (!isEmpty && unsavedFiles.length > 0) { saveMessageDialog.callBack = callBack; saveMessageDialog.open(); } else { projectIsClosing = true; doCloseProject(); if (callBack) callBack(); } } function saveProject() { if (!isEmpty) { projectSaving(); var projectData = saveProjectFile(); if (projectData !== null) projectSaved(); } } function saveProjectProperty(key, value) { var projectFile = projectPath + projectFileName; var json = fileIo.readFile(projectFile); if (!json) return; var projectData = JSON.parse(json); projectData[key] = value json = JSON.stringify(projectData, null, "\t"); fileIo.writeFile(projectFile, json); } function saveProjectFile() { if (!isEmpty) { var projectData = { files: [], title: projectTitle, deploymentAddresses: deploymentAddresses, applicationUrlEth: projectModel.applicationUrlEth, applicationUrlHttp: projectModel.applicationUrlHttp, deploymentDir: deploymentDialog.packageStep.packageDir, lastPackageDate: deploymentDialog.packageStep.lastPackageDate, deployBlockNumber: projectModel.deployBlockNumber, localPackageUrl: deploymentDialog.packageStep.localPackageUrl, deploymentTrHashes: JSON.stringify(projectModel.deploymentTrHashes), registerContentHashTrHash: projectModel.registerContentHashTrHash, registerUrlTrHash: projectModel.registerUrlTrHash, registerContentHashBlockNumber: projectModel.registerContentHashBlockNumber, registerUrlBlockNumber: projectModel.registerUrlBlockNumber, startUrl: mainContent.webView.relativePath() }; for (var i = 0; i < projectListModel.count; i++) projectData.files.push({ title: projectListModel.get(i).name, fileName: projectListModel.get(i).fileName, }); projectFileSaving(projectData); var json = JSON.stringify(projectData, null, "\t"); var projectFile = projectPath + "/" + projectFileName; fileIo.writeFile(projectFile, json); projectFileSaved(projectData); return projectData; } return null; } function loadProject(path) { closeProject(function() { console.log("Loading project at " + path); var projectFile = path + "/" + projectFileName; var json = fileIo.readFile(projectFile); if (!json) return; var projectData = JSON.parse(json); if (projectData.deploymentDir) projectModel.deploymentDir = projectData.deploymentDir if (projectData.applicationUrlEth) projectModel.applicationUrlEth = projectData.applicationUrlEth if (projectData.applicationUrlHttp) projectModel.applicationUrlHttp = projectData.applicationUrlHttp if (projectData.lastPackageDate) deploymentDialog.packageStep.lastPackageDate = projectData.lastPackageDate if (projectData.deployBlockNumber) projectModel.deployBlockNumber = projectData.deployBlockNumber if (projectData.localPackageUrl) deploymentDialog.packageStep.localPackageUrl = projectData.localPackageUrl if (projectData.deploymentTrHashes) projectModel.deploymentTrHashes = JSON.parse(projectData.deploymentTrHashes) if (projectData.registerUrlTrHash) projectModel.registerUrlTrHash = projectData.registerUrlTrHash if (projectData.registerContentHashTrHash) projectModel.registerContentHashTrHash = projectData.registerContentHashTrHash if (projectData.registerContentHashBlockNumber) projectModel.registerContentHashBlockNumber = projectData.registerContentHashBlockNumber if (projectData.registerUrlBlockNumber) projectModel.registerUrlBlockNumber = projectData.registerUrlBlockNumber if (projectData.startUrl) projectModel.startUrl = projectData.startUrl if (!projectData.title) { var parts = path.split("/"); projectData.title = parts[parts.length - 2]; } deploymentAddresses = projectData.deploymentAddresses ? projectData.deploymentAddresses : {}; projectTitle = projectData.title; if (path.lastIndexOf("/") === path.length - 1) path = path.substring(0, path.length - 1) projectPath = path; // all files/folders from the root path are included in Mix. if (!projectData.files) projectData.files = []; if (mainApplication.trackLastProject) projectSettings.lastProjectPath = path; projectLoading(projectData); //TODO: move this to codemodel var contractSources = {}; for (var d = 0; d < listModel.count; d++) { var doc = listModel.get(d); if (doc.isContract) projectModel.openDocument(doc.documentId) } projectLoaded() }); } function file(docData) { var fileName = docData.fileName var extension = fileName.substring(fileName.lastIndexOf("."), fileName.length); var path = docData.path var isContract = extension === ".sol"; var isHtml = extension === ".html"; var isCss = extension === ".css"; var isJs = extension === ".js"; var isImg = extension === ".png" || extension === ".gif" || extension === ".jpg" || extension === ".svg"; var syntaxMode = isContract ? "solidity" : isJs ? "javascript" : isHtml ? "htmlmixed" : isCss ? "css" : ""; var groupName = isContract ? qsTr("Contracts") : isJs ? qsTr("Javascript") : isHtml ? qsTr("Web Pages") : isCss ? qsTr("Styles") : isImg ? qsTr("Images") : qsTr("Misc"); var docData = { contract: false, readOnly: false, path: path, fileName: fileName, name: fileName, documentId: path, syntaxMode: syntaxMode, isText: isContract || isHtml || isCss || isJs, isContract: isContract, isHtml: isHtml, groupName: groupName }; return docData } function doCloseProject() { console.log("Closing project"); projectListModel.clear(); projectPath = ""; currentDocument = null projectClosed(); } function doCreateProject(title, path) { closeProject(function() { console.log("Creating project " + title + " at " + path); var dirPath = path + "/" + title fileIo.makeDir(dirPath); var projectFile = dirPath + "/" + projectFileName; var indexFile = "index.html"; var contractsFile = "contract.sol"; var projectData = { title: title, files: [ contractsFile, indexFile ] }; //TODO: copy from template if (!fileIo.fileExists(dirPath + "/" + indexFile)) fileIo.writeFile(dirPath + "/" + indexFile, htmlTemplate); if (!fileIo.fileExists(dirPath + "/" + contractsFile)) fileIo.writeFile(dirPath + "/" + contractsFile, contractTemplate); newProject(projectData); var json = JSON.stringify(projectData, null, "\t"); fileIo.writeFile(projectFile, json); loadProject(dirPath); }); } function newHtmlFile() { createAndAddFile("page", "html", htmlTemplate); } function newCssFile() { createAndAddFile("style", "css", "body {\n}\n"); } function newJsFile() { createAndAddFile("script", "js", "function foo() {\n}\n"); } function newContract() { var ctrName = "contract" + Object.keys(codeModel.contracts).length var ctr = basicContractTemplate.replace("FirstContract", ctrName) createAndAddFile("contract", "sol", ctr, ctrName + ".sol"); } function createAndAddFile(name, extension, content, fileName) { fileName = generateFileName(name, extension); var filePath = currentFolder + "/" + fileName; if (!fileIo.fileExists(filePath)) fileIo.writeFile(filePath, content); saveProjectFile(); documentAdded(filePath); } function generateFileName(name, extension) { var i = 1; do { var fileName = name + i + "." + extension; var filePath = currentFolder + "/" + fileName; i++; } while (fileIo.fileExists(filePath)); return fileName } function regenerateCompilationResult() { fileIo.deleteDir(compilationFolder) fileIo.makeDir(compilationFolder) var ctrJson = {} for (var c in codeModel.contracts) { var contract = codeModel.contracts[c] ctrJson[contract.documentId] = "" } for (var doc in ctrJson) saveContractCompilationResult(doc) } function saveContractCompilationResult(documentId) { if (!fileIo.dirExists(compilationFolder)) fileIo.makeDir(compilationFolder) var date = new Date() var ret = "/*\nGenerated by Mix\n" + date.toString() + "\n*/\n\n" var newCompilationResult = false for (var c in codeModel.contracts) { var contract = codeModel.contracts[c] if (contract.documentId === documentId) { newCompilationResult = true var ctr = { name: c, codeHex: contract.codeHex, abi: contract.contractInterface } ret += "var " + c + " = " + JSON.stringify(ctr, null, "\t") + "\n\n" } } if (newCompilationResult) fileIo.writeFile(compilationFolder + "/" + documentId.substring(documentId.lastIndexOf("/")) + ".js", ret) }
version https://git-lfs.github.com/spec/v1 oid sha256:5ef127d8cbe045d74b207fd89b56254b67bbdc7d4e989de89c2d9f1e9ad8a0d9 size 3278
CAAT.Module( { /** * @name Skeleton * @memberof CAAT.Module.Skeleton * @constructor */ defines : "CAAT.Module.Skeleton.Skeleton", depends : [ "CAAT.Module.Skeleton.Bone" ], extendsWith : { /** * @lends CAAT.Module.Skeleton.Skeleton.prototype */ bones : null, bonesArray : null, animation : null, root : null, currentAnimationName : null, skeletonDataFromFile : null, __init : function(skeletonDataFromFile) { this.bones= {}; this.bonesArray= []; this.animations= {}; // bones if (skeletonDataFromFile) { this.__setSkeleton( skeletonDataFromFile ); } }, getSkeletonDataFromFile : function() { return this.skeletonDataFromFile; }, __setSkeleton : function( skeletonDataFromFile ) { this.skeletonDataFromFile= skeletonDataFromFile; for ( var i=0; i<skeletonDataFromFile.bones.length; i++ ) { var boneInfo= skeletonDataFromFile.bones[i]; this.addBone(boneInfo); } }, setSkeletonFromFile : function(url) { var me= this; new CAAT.Module.Preloader.XHR().load( function( result, content ) { if (result==="ok" ) { me.__setSkeleton( JSON.parse(content) ); } }, url, false, "GET" ); return this; }, addAnimationFromFile : function(name, url) { var me= this; new CAAT.Module.Preloader.XHR().load( function( result, content ) { if (result==="ok" ) { me.addAnimation( name, JSON.parse(content) ); } }, url, false, "GET" ); return this; }, addAnimation : function(name, animation) { // bones animation for( var bonename in animation.bones ) { var boneanimation= animation.bones[bonename]; if ( boneanimation.rotate ) { for( var i=0; i<boneanimation.rotate.length-1; i++ ) { this.addRotationKeyframe( name, { boneId : bonename, angleStart : boneanimation.rotate[i].angle, angleEnd : boneanimation.rotate[i+1].angle, timeStart : boneanimation.rotate[i].time*1000, timeEnd : boneanimation.rotate[i+1].time*1000, curve : boneanimation.rotate[i].curve } ); } } if (boneanimation.translate) { for( var i=0; i<boneanimation.translate.length-1; i++ ) { this.addTranslationKeyframe( name, { boneId : bonename, startX : boneanimation.translate[i].x, startY : -boneanimation.translate[i].y, endX : boneanimation.translate[i+1].x, endY : -boneanimation.translate[i+1].y, timeStart : boneanimation.translate[i].time * 1000, timeEnd : boneanimation.translate[i+1].time * 1000, curve : "stepped" //boneanimation.translate[i].curve }); } } if ( boneanimation.scale ) { for( var i=0; i<boneanimation.scale.length-1; i++ ) { this.addScaleKeyframe( name, { boneId : bonename, startScaleX : boneanimation.rotate[i].x, endScaleX : boneanimation.rotate[i+1].x, startScaleY : boneanimation.rotate[i].y, endScaleY : boneanimation.rotate[i+1].y, timeStart : boneanimation.rotate[i].time*1000, timeEnd : boneanimation.rotate[i+1].time*1000, curve : boneanimation.rotate[i].curve } ); } } this.endKeyframes( name, bonename ); } if ( null===this.currentAnimationName ) { this.animations[name]= animation; this.setAnimation(name); } return this; }, setAnimation : function(name) { this.root.setAnimation( name ); this.currentAnimationName= name; }, getCurrentAnimationData : function() { return this.animations[ this.currentAnimationName ]; }, getAnimationDataByName : function(name) { return this.animations[name]; }, getNumBones : function() { return this.bonesArray.length; }, getRoot : function() { return this.root; }, calculate : function(time, animationTime) { this.root.apply(time, animationTime); }, getBoneById : function(id) { return this.bones[id]; }, getBoneByIndex : function(index) { return this.bonesArray[ index ]; }, addBone : function( boneInfo ) { var bone= new CAAT.Module.Skeleton.Bone(boneInfo.name); bone.setPosition( typeof boneInfo.x!=="undefined" ? boneInfo.x : 0, typeof boneInfo.y!=="undefined" ? boneInfo.y : 0 ); bone.setRotateTransform( boneInfo.rotation ? boneInfo.rotation : 0 ); bone.setSize( boneInfo.length ? boneInfo.length : 0, 0 ); this.bones[boneInfo.name]= bone; if (boneInfo.parent) { var parent= this.bones[boneInfo.parent]; if ( parent ) { parent.addBone(bone); } else { console.log("Referenced parent Bone '"+boneInfo.parent+"' which does not exist"); } } this.bonesArray.push(bone); // BUGBUG should be an explicit root bone identification. if (!this.root) { this.root= bone; } }, addRotationKeyframe : function( name, keyframeInfo ) { var bone= this.bones[ keyframeInfo.boneId ]; if ( bone ) { bone.addRotationKeyframe( name, keyframeInfo.angleStart, keyframeInfo.angleEnd, keyframeInfo.timeStart, keyframeInfo.timeEnd, keyframeInfo.curve ) } else { console.log("Rotation Keyframe for non-existant bone: '"+keyframeInfo.boneId+"'" ); } }, addScaleKeyframe : function( name, keyframeInfo ) { var bone= this.bones[ keyframeInfo.boneId ]; if ( bone ) { bone.addRotationKeyframe( name, keyframeInfo.startScaleX, keyframeInfo.endScaleX, keyframeInfo.startScaleY, keyframeInfo.endScaleY, keyframeInfo.timeStart, keyframeInfo.timeEnd, keyframeInfo.curve ) } else { console.log("Scale Keyframe for non-existant bone: '"+keyframeInfo.boneId+"'" ); } }, addTranslationKeyframe : function( name, keyframeInfo ) { var bone= this.bones[ keyframeInfo.boneId ]; if ( bone ) { bone.addTranslationKeyframe( name, keyframeInfo.startX, keyframeInfo.startY, keyframeInfo.endX, keyframeInfo.endY, keyframeInfo.timeStart, keyframeInfo.timeEnd, keyframeInfo.curve ) } else { console.log("Translation Keyframe for non-existant bone: '"+keyframeInfo.boneId+"'" ); } }, endKeyframes : function( name, boneId ) { var bone= this.bones[boneId]; if (bone) { bone.endTranslationKeyframes(name); bone.endRotationKeyframes(name); bone.endScaleKeyframes(name); } }, paint : function( actorMatrix, ctx ) { this.root.paint(actorMatrix,ctx); } } });
/* * env-spawn-test.js: Tests for supporting environment variables in the forever module * * (C) 2010 Nodejitsu Inc. * MIT LICENCE * */ var assert = require('assert'), path = require('path'), vows = require('vows'), forever = require('../lib/forever'), helpers = require('./helpers'); vows.describe('forever/spawn-options').addBatch({ "When using forever": { "an instance of forever.Monitor with valid options": { "passing environment variables to env-vars.js": { topic: function () { var that = this, child; this.env = { FOO: 'foo', BAR: 'bar' }; child = new (forever.Monitor)(path.join(__dirname, '..', 'examples', 'env-vars.js'), { max: 1, silent: true, minUptime: 0, env: this.env }); child.on('stdout', function (data) { that.stdout = data.toString(); }); child.on('exit', this.callback.bind({}, null)); child.start(); }, "should pass the environment variables to the child": function (err, child) { assert.equal(child.times, 1); assert.equal(this.stdout, JSON.stringify(this.env)); } }, "passing a custom cwd to custom-cwd.js": { topic: function () { var that = this, child; this.cwd = path.join(__dirname, '..'); child = new (forever.Monitor)(path.join(__dirname, '..', 'examples', 'custom-cwd.js'), { max: 1, silent: true, minUptime: 0, cwd: this.cwd }); child.on('stdout', function (data) { that.stdout = data.toString(); }); child.on('exit', this.callback.bind({}, null)); child.start(); }, "should setup the child to run in the target directory": function (err, child) { assert.equal(child.times, 1); assert.equal(this.stdout, this.cwd); } }, "setting `hideEnv` when spawning all-env-vars.js": { topic: function () { var that = this, child; this.hideEnv = [ 'USER', 'OLDPWD' ]; child = new (forever.Monitor)(path.join(__dirname, '..', 'examples', 'all-env-vars.js'), { max: 1, silent: true, minUptime: 0, hideEnv: this.hideEnv }); child.on('stdout', function (data) { that.env = Object.keys(JSON.parse(data.toString())); }); child.on('exit', this.callback.bind(this, null)); child.start(); }, "should hide the environment variables passed to the child": function (err, child) { var that = this; assert.equal(child.times, 1); this.hideEnv.forEach(function (key) { assert.isTrue(that.env.indexOf(key) === -1); }); } }, } } }).export(module);
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var tests = [ function() { function AsmModuleDouble() { "use asm"; function test0(x) { x = +x; return +test0sub(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 0.5, 10.5); } function test0sub(a,b,c,d,e,f,g,h,j,i,k) { a = +a; b = +b; c = +c; d = +d; e = +e; f = +f; g = +g; h = +h; j = +j; i = +i; k = +k; return +(a); } function test1(x) { x = +x; return +test1sub(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 0.5, 10.5); } function test1sub(a,b,c,d,e,f,g,h,j,i,k) { a = +a; b = +b; c = +c; d = +d; e = +e; f = +f; g = +g; h = +h; j = +j; i = +i; k = +k; return +(f); } function test2(x) { x = +x; return +test2sub(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 0.5, 10.5); } function test2sub(a,b,c,d,e,f,g,h,j,i,k) { a = +a; b = +b; c = +c; d = +d; e = +e; f = +f; g = +g; h = +h; j = +j; i = +i; k = +k; return +(g); } function test3(x) { x = +x; return +test3sub(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 0.5, 10.5); } function test3sub(a,b,c,d,e,f,g,h,j,i,k) { a = +a; b = +b; c = +c; d = +d; e = +e; f = +f; g = +g; h = +h; j = +j; i = +i; k = +k; return +(h); } function test4(x) { x = +x; return +test4sub(1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 0.5, 10.5); } function test4sub(a,b,c,d,e,f,g,h,j,i,k) { a = +a; b = +b; c = +c; d = +d; e = +e; f = +f; g = +g; h = +h; j = +j; i = +i; k = +k; return +(k); } return { test0: test0, test1: test1, test2: test2, test3: test3, test4: test4 }; } var asmModuleDouble = AsmModuleDouble(); if (asmModuleDouble.test0(2, 3, 4) != 1.5) throw ('a - 1st arg. storage has failed.'); if (asmModuleDouble.test1(2, 3, 4) != 6.5) throw ('f - 6th arg. storage has failed.'); if (asmModuleDouble.test2(2, 3, 4) != 7.5) throw ('g - 7th arg. storage has failed.'); if (asmModuleDouble.test3(2, 3, 4) != 8.5) throw ('h - 8th arg. storage has failed.'); if (asmModuleDouble.test4(2, 3, 4) != 10.5) throw ('k - 11th arg. storage has failed.'); }, function() { function asm() { "use asm" function SubCount(a,b,c,d,e,f,g,h,j,k,l) { a = +a; b = +b; c = c | 0; d = d | 0; e = +e; f = +f; g = +g; h = +h; j = +j; k = +k; l = +l; return +(l); } function Count(a) { a = +a; return +SubCount(3.2, 1.2, 2, 5, 6.33, 4.88, 1.2, 2.6, 3.99, 1.2, 2.6); } return { Count: Count }; } var total = 0; var fnc = asm (); for(var i = 0;i < 1e6; i++) { total += fnc.Count(1, 2); } if (parseInt(total) != parseInt(1e6 * 2.6)) throw new Error('Test Failed -> ' + total); }, function() { function asm() { "use asm" function SubCount(a,b,c,d,e,f,g) { a = a | 0; b = b | 0; c = c | 0; d = d | 0; e = e | 0; f = f | 0; g = +g; return +(g); } function Count(a) { a = +a; return +SubCount(1, 2, 3, 4, 5, 6, 1.3); } return { Count: Count }; } var total = 0; var fnc = asm (); for(var i = 0;i < 1e6; i++) { total += fnc.Count(1, 2); } if (parseInt(total) != parseInt(1e6 * 1.3)) throw new Error('Test Failed -> ' + total); }]; for(var i = 0; i < tests.length; i++) tests[i](); print('PASS')
const os = require('os'); const path = require('path'); const view = require('think-view'); const model = require('think-model'); const cache = require('think-cache'); const session = require('think-session'); const ROOT_PATH = think.env === 'now' ? os.tmpdir() : think.ROOT_PATH; module.exports = [ view, // make application support view model(think.app), cache, session, { think: { TMPDIR_PATH: path.join(ROOT_PATH, 'runtime', 'tmp'), RUNTIME_PATH: path.join(ROOT_PATH, 'runtime'), RESOURCE_PATH: path.join(think.ROOT_PATH, 'www'), UPLOAD_PATH: path.join(think.ROOT_PATH, 'www', 'static/upload'), UPLOAD_BASE_URL: '' } } ];
var BootLogo = { show: function(cb) { Sfx.play('burningtomato.wav'); $('#burningtomato').delay(500).fadeIn(500, function() { window.setTimeout(function() { $('#burningtomato').fadeOut(500, cb); }, 1500) }); } };
;(function(Form, Editor) { module('Checkboxes', { setup: function() { this.sinon = sinon.sandbox.create(); }, teardown: function() { this.sinon.restore(); } }); same = deepEqual; var schema = { options: ['Sterling', 'Lana', 'Cyril', 'Cheryl', 'Pam', 'Doctor Krieger'] }; test('Options as array of objects', function() { var editor = new Editor({ schema: { options: [ { val: 0, label: "Option 1" }, { val: 1, label: "Option 2" }, { val: 2, label: "Option 3" } ] } }).render(); var checkboxes = editor.$el.find("input[type=checkbox]"); var labels = editor.$el.find("label"); equal(checkboxes.length, 3); equal(checkboxes.length, labels.length); equal(labels.first().html(), "Option 1"); equal(labels.last().html(), "Option 3"); equal(checkboxes.first().val(), "0"); equal(checkboxes.last().val(), "2"); }); test('Options as array of group objects', function() { var editor = new Editor({ schema: { options: [ { group: 'North America', options: [ { val: 'ca', label: 'Canada' }, { val: 'us', label: 'United States' } ], }, { group: 'Europe', options: [ { val: 'es', label: 'Spain' }, { val: 'fr', label: 'France' }, { val: 'uk', label: 'United Kingdom' } ] } ] } }).render(); var checkboxes = editor.$el.find("input[type=checkbox]"); var labels = editor.$el.find("label"); var fieldset = editor.$el.find("fieldset"); var uniqueLabels = []; equal(checkboxes.length, 5); equal(checkboxes.length, labels.length); equal(fieldset.length, 2); labels.each(function(){ if(uniqueLabels.indexOf($(this).attr('for')) == -1 ) uniqueLabels.push($(this).attr('for')); }); equal(checkboxes.length, uniqueLabels.length); }); test('Default value', function() { var editor = new Editor({ schema: schema }).render(); var value = editor.getValue(); equal(_.isEqual(value, []), true); }); test('Custom value', function() { var editor = new Editor({ value: ['Cyril'], schema: schema }).render(); var value = editor.getValue(); var expected = ['Cyril']; equal(_.isEqual(expected, value), true); }); test('Throws errors if no options', function () { throws(function () { var editor = new Editor({schema: {}}); }, /Missing required/, 'ERROR: Accepted a new Checkboxes editor with no options.'); }); // Value from model doesn't work here as the value must be an array. test('Correct type', function() { var editor = new Editor({ schema: schema }).render(); equal($(editor.el).get(0).tagName, 'UL'); notEqual($(editor.el).find('input[type=checkbox]').length, 0); }); test('setting value with one item', function() { var editor = new Editor({ schema: schema }).render(); editor.setValue(['Lana']); deepEqual(editor.getValue(), ['Lana']); equal($(editor.el).find('input[type=checkbox]:checked').length, 1); }); test('setting value with multiple items, including a value with a space', function() { var editor = new Editor({ schema: schema }).render(); editor.setValue(['Lana', 'Doctor Krieger']); deepEqual(editor.getValue(), ['Lana', 'Doctor Krieger']); equal($(editor.el).find('input[type=checkbox]:checked').length, 2); }); module('Checkboxes events', { setup: function() { this.sinon = sinon.sandbox.create(); this.editor = new Editor({ schema: schema }).render(); $('body').append(this.editor.el); }, teardown: function() { this.sinon.restore(); this.editor.remove(); } }); test("focus() - gives focus to editor and its first checkbox", function() { var editor = this.editor; editor.focus(); ok(editor.hasFocus); ok(editor.$('input[type=checkbox]').first().is(':focus')); editor.blur(); stop(); setTimeout(function() { start(); }, 0); }); test("focus() - triggers the 'focus' event", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('focus', spy); editor.focus(); stop(); setTimeout(function() { ok(spy.called); ok(spy.calledWith(editor)); editor.blur(); setTimeout(function() { start(); }, 0); }, 0); }); test("blur() - removes focus from the editor and its focused checkbox", function() { var editor = this.editor; editor.focus(); editor.blur(); stop(); setTimeout(function() { ok(!editor.hasFocus); ok(!editor.$('input[type=checkbox]').first().is(':focus')); start(); }, 0); }); test("blur() - triggers the 'blur' event", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('blur', spy); editor.blur(); stop(); setTimeout(function() { ok(spy.called); ok(spy.calledWith(editor)); start(); }, 0); }); test("'change' event - is triggered when a checkbox is clicked", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('change', spy); editor.$("input[type=checkbox]").first().click(); ok(spy.called); ok(spy.calledWith(editor)); editor.$("input[type=checkbox]").val([null]); }); test("'focus' event - bubbles up from checkbox when editor doesn't have focus", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('focus', spy); editor.$("input[type=checkbox]").first().focus(); ok(spy.called); ok(spy.calledWith(editor)); editor.blur(); stop(); setTimeout(function() { start(); }, 0); }); test("'focus' event - doesn't bubble up from checkbox when editor already has focus", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('focus', spy); editor.$("input[type=checkbox]").focus(); ok(!spy.called); editor.blur(); stop(); setTimeout(function() { start(); }, 0); }); test("'blur' event - bubbles up from checkbox when editor has focus and we're not focusing on another one of the editor's checkboxes", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('blur', spy); editor.$("input[type=checkbox]").first().blur(); stop(); setTimeout(function() { ok(spy.called); ok(spy.calledWith(editor)); start(); }, 0); }); test("'blur' event - doesn't bubble up from checkbox when editor has focus and we're focusing on another one of the editor's checkboxes", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('blur', spy); editor.$("input[type=checkbox]:eq(0)").blur(); editor.$("input[type=checkbox]:eq(1)").focus(); stop(); setTimeout(function() { ok(!spy.called); editor.blur(); setTimeout(function() { start(); }, 0); }, 0); }); test("'blur' event - doesn't bubble up from checkbox when editor doesn't have focus", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('blur', spy); editor.$("input[type=checkbox]").blur(); stop(); setTimeout(function() { ok(!spy.called); start(); }, 0); }); module('Checkboxes Text Escaping', { setup: function() { this.sinon = sinon.sandbox.create(); this.options = [ { val: '"/><script>throw("XSS Success");</script>', label: '"/><script>throw("XSS Success");</script>' }, { val: '\"?\'\/><script>throw("XSS Success");</script>', label: '\"?\'\/><script>throw("XSS Success");</script>', }, { val: '><b>HTML</b><', label: '><div class=>HTML</b><', } ]; this.editor = new Editor({ schema: { options: this.options } }).render(); $('body').append(this.editor.el); }, teardown: function() { this.sinon.restore(); this.editor.remove(); } }); test('options content gets properly escaped', function() { same( this.editor.schema.options, this.options ); //What an awful string. //CAN'T have white-space on the left, or the string will no longer match //If this bothers you aesthetically, can switch it to concat syntax var escapedHTML = "<li><input type=\"checkbox\" name=\"\" id=\"undefined-0\" value=\"&quot;\ /><script>throw(&quot;XSS Success&quot;);</script>\"><label for=\"undefined-0\">\"/&gt;&lt;script\ &gt;throw(\"XSS Success\");&lt;/script&gt;</label></li><li><input type=\"checkbox\" name=\"\" \ id=\"undefined-1\" value=\"&quot;?'/><script>throw(&quot;XSS Success&quot;);</script>\"><label \ for=\"undefined-1\">\"?'/&gt;&lt;script&gt;throw(\"XSS Success\");&lt;/script&gt;</label></li><li>\ <input type=\"checkbox\" name=\"\" id=\"undefined-2\" value=\"><b>HTML</b><\"><label \ for=\"undefined-2\">&gt;&lt;div class=&gt;HTML&lt;/b&gt;&lt;</label></li>"; same( this.editor.$el.html(), escapedHTML ); same( this.editor.$('input').val(), this.options[0].val ); same( this.editor.$('label').first().text(), this.options[0].label ); same( this.editor.$('label').first().html(), '\"/&gt;&lt;script&gt;throw(\"XSS Success\");&lt;/script&gt;' ); same( this.editor.$('label').text(), "\"/><script>throw(\"XSS Success\");</script>\"?'/><script>throw(\"XSS Success\");</script>><div class=>HTML</b><" ); }); test('options object content gets properly escaped', function() { var options = { key1: '><b>HTML</b><', key2: '><div class=>HTML</b><' }; var editor = new Editor({ schema: { options: options } }).render(); same( editor.schema.options, options ); //What an awful string. //CAN'T have white-space on the left, or the string will no longer match //If this bothers you aesthetically, can switch it to concat syntax var escapedHTML = "<li><input type=\"checkbox\" name=\"\" id=\"undefined-0\" \ value=\"key1\"><label for=\"undefined-0\">&gt;&lt;b&gt;HTML&lt;/b&gt;&lt;</label>\ </li><li><input type=\"checkbox\" name=\"\" id=\"undefined-1\" value=\"key2\">\ <label for=\"undefined-1\">&gt;&lt;div class=&gt;HTML&lt;/b&gt;&lt;</label></li>"; same( editor.$el.html(), escapedHTML ); same( editor.$('input').val(), _.keys(options)[0] ); same( editor.$('label').first().text(), options.key1 ); same( editor.$('label').first().html(), '&gt;&lt;b&gt;HTML&lt;/b&gt;&lt;' ); same( editor.$('label').text(), '><b>HTML</b><><div class=>HTML</b><' ); }); test('options labels can be labelHTML, which will not be escaped', function() { var options = [ { val: '><b>HTML</b><', labelHTML: '><div class=>HTML</b><', label: 'will be ignored' } ]; var editor = new Editor({ schema: { options: options } }).render(); same( editor.schema.options, options ); //What an awful string. //CAN'T have white-space on the left, or the string will no longer match //If this bothers you aesthetically, can switch it to concat syntax var escapedHTML = "<li><input type=\"checkbox\" name=\"\" id=\"undefined-0\" value=\"><b>\ HTML</b><\"><label for=\"undefined-0\">&gt;<div class=\"\">HTML&lt;</div></label></li>"; same( editor.$el.html(), escapedHTML ); same( editor.$('input').val(), options[0].val ); //Note that in these 3 results, the labelHTML has //been transformed because the HTML was invalid same( editor.$('label').first().text(), ">HTML<" ); same( editor.$('label').first().html(), '&gt;<div class=\"\">HTML&lt;</div>' ); same( editor.$('label').text(), '>HTML<' ); }); test('option groups content gets properly escaped', function() { var options = [{ group: '"/><script>throw("XSS Success");</script>', options: [ { val: '"/><script>throw("XSS Success");</script>', label: '"/><script>throw("XSS Success");</script>' }, { val: '\"?\'\/><script>throw("XSS Success");</script>', label: '\"?\'\/><script>throw("XSS Success");</script>', }, { val: '><b>HTML</b><', label: '><div class=>HTML</b><', } ] }]; var editor = new Editor({ schema: { options: options } }).render(); same( editor.schema.options, options ); //What an awful string. //CAN'T have white-space on the left, or the string will no longer match //If this bothers you aesthetically, can switch it to concat syntax var escapedHTML = "<fieldset class=\"group\"><legend>\"/&gt;&lt;script&gt;\ throw(\"XSS Success\");&lt;/script&gt;</legend><li><input type=\"checkbox\" \ name=\"\" id=\"undefined-0-0\" value=\"&quot;/><script>throw(&quot;XSS Success&quot;)\ ;</script>\"><label for=\"undefined-0-0\">\"/&gt;&lt;script&gt;throw(\"XSS Success\");\ &lt;/script&gt;</label></li><li><input type=\"checkbox\" name=\"\" id=\"undefined-0-1\" \ value=\"&quot;?'/><script>throw(&quot;XSS Success&quot;);</script>\"><label for=\"undefined-\ 0-1\">\"?'/&gt;&lt;script&gt;throw(\"XSS Success\");&lt;/script&gt;</label></li><li>\ <input type=\"checkbox\" name=\"\" id=\"undefined-0-2\" value=\"><b>HTML</b><\"><label \ for=\"undefined-0-2\">&gt;&lt;div class=&gt;HTML&lt;/b&gt;&lt;</label></li></fieldset>"; same( editor.$el.html(), escapedHTML ); same( editor.$('input').val(), options[0].options[0].val ); same( editor.$('label').first().text(), options[0].options[0].label ); same( editor.$('label').first().html(), '\"/&gt;&lt;script&gt;throw(\"XSS Success\");&lt;/script&gt;' ); same( editor.$('label').text(), "\"/><script>throw(\"XSS Success\");</script>\"?'/><script>throw(\"XSS Success\");</script>><div class=>HTML</b><" ); }); })(Backbone.Form, Backbone.Form.editors.Checkboxes);
var Readable = require('stream').Readable; var through = require('through'); var read = require('./'); var test = require('tape'); test('push read', function(t){ var stream = through(); read(stream, function(err, val){ t.error(err); t.equal(val, 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val, 'bar'); read(stream, function(err, val){ t.error(err); t.equal(val, undefined); t.end(); }); }); }); stream.queue('foo'); stream.queue('bar'); stream.queue(null); }); test('push error', function(t){ var stream = through(); read(stream, function(err){ t.ok(err); t.end(); }); stream.emit('error', new Error); }); test('push backpressure', function(t){ var stream = through(); read(stream, function(err, val){ t.error(err); t.equal(val, 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val, 'bar'); read(stream, function(err, val){ t.error(err); t.equal(val, undefined); t.end(); }); }); }); setTimeout(function(){ stream.queue('foo'); setTimeout(function(){ stream.queue('bar'); setTimeout(function(){ stream.queue(null); }); }); }); }); test('pull read', function(t){ var times = 3; var stream = Readable(); stream._read = function(){ if (!times--) return stream.push(null); setTimeout(function() { stream.push('foo'); }); }; read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val, null); t.end(); }); }); }); }); }); test('pull read 2', function(t){ var times = 2; var stream = Readable(); stream._read = function(){ setTimeout(function() { if (times-- > 0) { stream.push('foo'); stream.push('bar'); } else { stream.push(null); } }); }; read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'bar'); read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'foo'); read(stream, function(err, val){ t.error(err); t.equal(val.toString(), 'bar'); read(stream, function(err, val){ t.error(err); t.equal(val, null); t.end(); }); }); }); }); }); }); test('pull end', function(t){ var stream = Readable(); stream.push(null); read(stream, function(err, val){ t.error(err); t.equal(val, null); read(stream, function(err, val){ t.error(err); t.equal(val, undefined); t.end(); }); }); }); test('pull error', function(t){ var stream = Readable(); stream._read = function() { stream.emit('error', new Error); }; read(stream, function(err){ t.ok(err); t.end(); }); }); test('pull double end', function(t){ t.plan(1); var stream = Readable(); stream._read = function(){ this.push(null) }; read(stream, function(err, val){ t.equal(val, null); }); stream.emit('end'); });
/*! * @license deepcopy.js Copyright(c) 2013 sasa+1 * https://github.com/sasaplus1/deepcopy.js * Released under the MIT license. */ /** * export to AMD/CommonJS/global. * * @param {Object} global global object. * @param {Function} factory factory method. */ (function(global, factory) { 'use strict'; if (typeof define === 'function' && !!define.amd) { define(factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { global.deepcopy = factory(); } }(this, function() { 'use strict'; var isNode, util, isBuffer, getKeys, getSymbols, indexOfArray; // is node.js/io.js? isNode = (typeof process !== 'undefined' && typeof require !== 'undefined'); // fallback util module for browser. util = (isNode) ? require('util') : (function() { function isArray(value) { return (typeof value === 'object' && Object.prototype.toString.call(value) === '[object Array]'); } function isDate(value) { return (typeof value === 'object' && Object.prototype.toString.call(value) === '[object Date]'); } function isRegExp(value) { return (typeof value === 'object' && Object.prototype.toString.call(value) === '[object RegExp]'); } function isSymbol(value) { return (typeof value === 'symbol'); } return { isArray: (typeof Array.isArray === 'function') ? function(obj) { return Array.isArray(obj); } : isArray, isDate: isDate, isRegExp: isRegExp, isSymbol: (typeof Symbol === 'function') ? isSymbol : function() { // always return false when Symbol is not supported. return false; } }; }()); // fallback Buffer.isBuffer isBuffer = (isNode) ? function(obj) { return Buffer.isBuffer(obj); } : function() { // if browser, always return false return false; }; // fallback Object.keys for old browsers. getKeys = (typeof Object.keys === 'function') ? function(obj) { return Object.keys(obj); } : function(obj) { var keys = [], key; if (obj === null || typeof obj !== 'object') { throw new TypeError('obj is not an Object'); } for (key in obj) { obj.hasOwnProperty(key) && keys.push(key); } return keys; }; // get symbols in object. getSymbols = (typeof Symbol === 'function') ? function(obj) { return Object.getOwnPropertySymbols(obj); } : function() { // always return empty array when Symbol is not supported. return []; }; // fallback Array#indexOf for old browsers. indexOfArray = (typeof Array.prototype.indexOf === 'function') ? function(array, searchElement) { return array.indexOf(searchElement); } : function(array, searchElement) { var i, len; if (!util.isArray(array)) { throw new TypeError('array is not an Array'); } for (i = 0, len = array.length; i < len; ++i) { if (array[i] === searchElement) { return i; } } return -1; }; /** * recursive deep copy for value. * * @private * @param {*} value copy target. * @param {*} clone * @param {Array} visited * @param {Array} reference * @return {*} copied value. */ function copyValue_(value, clone, visited, reference) { var str, pos, buf, keys, i, len, key, val, idx, obj, ref; // number, string, boolean, null, undefined, function and symbol. if (value === null || typeof value !== 'object') { return value; } // Date. if (util.isDate(value)) { // Firefox need to convert to Number // // Firefox: // var date = new Date; // +date; // 1420909365967 // +new Date(date); // 1420909365000 // +new Date(+date); // 1420909365967 // Chrome: // var date = new Date; // +date; // 1420909757913 // +new Date(date); // 1420909757913 // +new Date(+date); // 1420909757913 return new Date(+value); } // RegExp. if (util.isRegExp(value)) { // Chrome, Safari: // (new RegExp).source => "(?:)" // Firefox: // (new RegExp).source => "" // Chrome, Safari, Firefox // String(new RegExp) => "/(?:)/" str = String(value); pos = str.lastIndexOf('/'); return new RegExp(str.slice(1, pos), str.slice(pos + 1)); } // Buffer, node.js only. if (isBuffer(value)) { buf = new Buffer(value.length); value.copy(buf); return buf; } // Object or Array. keys = getKeys(value).concat(getSymbols(value)); for (i = 0, len = keys.length; i < len; ++i) { key = keys[i]; val = value[key]; if (val !== null && typeof val === 'object') { idx = indexOfArray(visited, val); if (idx === -1) { // not circular reference obj = (util.isArray(val)) ? [] : {}; visited.push(val); reference.push(obj); } else { // circular reference ref = reference[idx]; } } clone[key] = ref || copyValue_(val, obj, visited, reference); } return clone; } /** * deep copy for value. * * @param {*} value copy target. */ function deepcopy(value) { var clone = (util.isArray(value)) ? [] : {}, visited = [value], reference = [clone]; return copyValue_(value, clone, visited, reference); } return deepcopy; }));
THREE.LineGeometry = function () { THREE.LineSegmentsGeometry.call( this ); this.type = 'LineGeometry'; }; THREE.LineGeometry.prototype = Object.assign( Object.create( THREE.LineSegmentsGeometry.prototype ), { constructor: THREE.LineGeometry, isLineGeometry: true, setPositions: function ( array ) { // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format var length = array.length - 3; var points = new Float32Array( 2 * length ); for ( var i = 0; i < length; i += 3 ) { points[ 2 * i ] = array[ i ]; points[ 2 * i + 1 ] = array[ i + 1 ]; points[ 2 * i + 2 ] = array[ i + 2 ]; points[ 2 * i + 3 ] = array[ i + 3 ]; points[ 2 * i + 4 ] = array[ i + 4 ]; points[ 2 * i + 5 ] = array[ i + 5 ]; } THREE.LineSegmentsGeometry.prototype.setPositions.call( this, points ); return this; }, setColors: function ( array ) { // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format var length = array.length - 3; var colors = new Float32Array( 2 * length ); for ( var i = 0; i < length; i += 3 ) { colors[ 2 * i ] = array[ i ]; colors[ 2 * i + 1 ] = array[ i + 1 ]; colors[ 2 * i + 2 ] = array[ i + 2 ]; colors[ 2 * i + 3 ] = array[ i + 3 ]; colors[ 2 * i + 4 ] = array[ i + 4 ]; colors[ 2 * i + 5 ] = array[ i + 5 ]; } THREE.LineSegmentsGeometry.prototype.setColors.call( this, colors ); return this; }, fromLine: function ( line ) { var geometry = line.geometry; if ( geometry.isGeometry ) { console.error( 'THREE.LineGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); return; } else if ( geometry.isBufferGeometry ) { this.setPositions( geometry.attributes.position.array ); // assumes non-indexed } // set colors, maybe return this; }, copy: function ( /* source */ ) { // todo return this; } } );
angular.module('bosApp', ['ja.qr']). controller('saleCtrl', function ($scope) { $scope.merchantAddress = '1Akq3sCaNZLoE2RmrBCvN8paDGq1HiKow5'; $scope.saleAmount = ''; $scope.saleQr = function() { return 'bitcoin:' + $scope.merchantAddress + '?amount=' + $scope.saleAmount; }; $scope.size = 200; $scope.correctionLevel = ''; $scope.typeNumber = 0; $scope.inputMode = ''; $scope.image = true; });
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * sisane: The stunning micro-library that helps you to develop easily * AJAX web applications by using Angular.js 1.x & sisane-server * sisane is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * 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. * */ 'use strict'; moduloTipodiagnostico.controller('TipodiagnosticoRemovepopController', ['$scope', '$routeParams', 'serverService', 'tipodiagnosticoService', '$location', '$uibModalInstance', 'id', function ($scope, $routeParams, serverService, tipodiagnosticoService, $location, $uibModalInstance, id) { $scope.fields = tipodiagnosticoService.getFields(); $scope.obtitle = tipodiagnosticoService.getObTitle(); $scope.icon = tipodiagnosticoService.getIcon(); $scope.ob = tipodiagnosticoService.getTitle(); $scope.title = "Borrado de " + $scope.obtitle; $scope.id = id; $scope.status = null; $scope.debugging = serverService.debugging(); function getData() { serverService.promise_getOne($scope.ob, $scope.id).then(function (response) { if (response.status == 200) { if (response.data.status == 200) { $scope.status = null; $scope.bean = response.data.message; } else { $scope.status = "Error en la recepción de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } }).catch(function (data) { $scope.status = "Error en la recepción de datos del servidor"; }); } $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); } $scope.remove = function () { serverService.promise_removeOne($scope.ob, $scope.id).then(function (response) { if (response.status == 200) { if (response.data.status == 200) { if (response.data.message == 1) { $scope.status = "El registro " + $scope.obtitle + " se ha eliminado."; $uibModalInstance.close(true); getData(); return false; } else { $scope.status = "Error en el borrado de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } }).catch(function (data) { $scope.status = "Error en la recepción de datos del servidor"; }); } getData(); }]);
import { TAPi18n } from 'meteor/rocketchat:tap-i18n'; import { settings } from '../../settings'; import { callbacks } from '../../callbacks'; /* * MapView is a named function that will replace geolocation in messages with a Google Static Map * @param {Object} message - The message object */ function MapView(message) { // get MapView settings const mv_googlekey = settings.get('MapView_GMapsAPIKey'); if (message.location) { // GeoJSON is reversed - ie. [lng, lat] const [longitude, latitude] = message.location.coordinates; // confirm we have an api key set, and generate the html required for the mapview if (mv_googlekey && mv_googlekey.length) { message.html = `<a href="https://maps.google.com/maps?daddr=${ latitude },${ longitude }" target="_blank"><img src="https://maps.googleapis.com/maps/api/staticmap?zoom=14&size=250x250&markers=color:gray%7Clabel:%7C${ latitude },${ longitude }&key=${ mv_googlekey }" /></a>`; } else { message.html = `<a href="https://maps.google.com/maps?daddr=${ latitude },${ longitude }" target="_blank">${ TAPi18n.__('Shared_Location') }</a>`; } } return message; } callbacks.add('renderMessage', MapView, callbacks.priority.HIGH, 'mapview');
//From http://stackoverflow.com/questions/13046401/how-to-set-selected-select-option-in-handlebars-template //Update to work with Rhino which could not take a regex, or use jquery unlike many of the examples Handlebars.registerHelper('toString', function(context) { if(context === undefined || context === null){ return ""; } return context.toString(); });
/** * @fileoverview RaphaelLineTypeBase is base class for line type renderer. * @author NHN. * FE Development Lab <dl_javascript@nhn.com> */ import raphaelRenderUtil from './raphaelRenderUtil'; import renderUtil from '../helpers/renderUtil'; import predicate from '../helpers/predicate'; import arrayUtil from '../helpers/arrayUtil'; import chartConst from '../const'; import snippet from 'tui-code-snippet'; const {browser} = snippet; const IS_LTE_IE8 = browser.msie && browser.version <= 8; const ANIMATION_DURATION = 700; const DEFAULT_DOT_RADIUS = 6; const SELECTION_DOT_RADIUS = 7; const DE_EMPHASIS_OPACITY = 0.3; const MOVING_ANIMATION_DURATION = 300; const CHART_HOVER_STATUS_OVER = 'over'; const CHART_HOVER_STATUS_OUT = 'out'; /** * @classdesc RaphaelLineTypeBase is base for line type renderer. * @class RaphaelLineTypeBase * @private */ class RaphaelLineTypeBase { /** * Make lines path. * @param {Array.<{left: number, top: number, startTop: number}>} positions positions * @param {?string} [posTopType='top'] position top type * @param {boolean} [connectNulls] - boolean value connect nulls or not * @returns {Array.<string | number>} paths * @private */ _makeLinesPath(positions, posTopType, connectNulls) { let path = []; let prevMissing = false; posTopType = posTopType || 'top'; [].concat(positions).forEach(position => { const pathCommand = (prevMissing && !connectNulls) ? 'M' : 'L'; if (position) { path.push([pathCommand, position.left, position[posTopType]]); if (prevMissing) { prevMissing = false; } } else { prevMissing = true; } }); path = [].concat(...path); if (path.length > 0) { path[0] = 'M'; } return path; } /** * Get anchor. (http://raphaeljs.com/analytics.js) * @param {{left: number, top: number}} fromPos from position * @param {{left: number, top: number}} pos position * @param {{left: number, top: number}} nextPos next position * @param {?boolean} [isReverseDirection] - True when the line is drawn from right to left * @returns {{x1: number, y1: number, x2: number, y2: number}} anchor * @private */ _getAnchor(fromPos, pos, nextPos, isReverseDirection) { const l1 = (pos.left - fromPos.left) / 2; const l2 = (nextPos.left - pos.left) / 2; let a, b; if (isReverseDirection) { a = Math.atan((fromPos.left - pos.left) / Math.abs(fromPos.top - pos.top)); b = Math.atan((pos.left - nextPos.left) / Math.abs(nextPos.top - pos.top)); } else { a = Math.atan((pos.left - fromPos.left) / Math.abs(pos.top - fromPos.top)); b = Math.atan((nextPos.left - pos.left) / Math.abs(pos.top - nextPos.top)); } a = fromPos.top < pos.top ? Math.PI - a : a; b = nextPos.top < pos.top ? Math.PI - b : b; const alpha = (Math.PI / 2) - (((a + b) % (Math.PI * 2)) / 2); const dx1 = l1 * Math.sin(alpha + a); const dy1 = l1 * Math.cos(alpha + a); const dx2 = l2 * Math.sin(alpha + b); const dy2 = l2 * Math.cos(alpha + b); const result = { x1: pos.left - dx1, y1: pos.top + dy1, x2: pos.left + dx2, y2: pos.top + dy2 }; if (isReverseDirection) { result.y1 = pos.top - dy1; result.y2 = pos.top - dy2; } return result; } /** * Get spline positions groups which is divided with null data value. * If series has not divided positions, it returns only one positions group. * @param {Array.<object>} positions positions array * @param {boolean} connectNulls option of connect line of both null data's side * @Returns {Array.<Array.<object>>} * @private */ _getSplinePositionsGroups(positions, connectNulls) { const positionsGroups = []; let positionsGroup = []; positions.forEach((position, index) => { const isLastIndex = index === positions.length - 1; if (position) { positionsGroup.push(position); } if ((!position && positionsGroup.length > 0 && !connectNulls) || isLastIndex) { positionsGroups.push(positionsGroup); positionsGroup = []; } }); return positionsGroups; } /** * Get spline partial paths * @param {Array.<Array.<object>>} positionsGroups positions groups * @param {?boolean} [isReverseDirection] - True when the line is drawn from right to left * @returns {Array.<Array.<Array>>} * @private */ _getSplinePartialPaths(positionsGroups, isReverseDirection) { const paths = []; let lastPos, positionsLen, fromPos, middlePositions, path; positionsGroups.forEach(dataPositions => { let [prevPos] = dataPositions; const firstPos = prevPos; positionsLen = dataPositions.length; fromPos = firstPos; lastPos = dataPositions[positionsLen - 1]; middlePositions = dataPositions.slice(1).slice(0, positionsLen - 2); path = middlePositions.map((position, index) => { const nextPos = dataPositions[index + 2]; const anchor = this._getAnchor(fromPos, position, nextPos, isReverseDirection); fromPos = position; if (Math.abs(anchor.y1 - prevPos.top) > Math.abs(prevPos.top - position.top)) { anchor.y1 = position.top; } if (Math.abs(anchor.y2 - nextPos.top) > Math.abs(nextPos.top - position.top)) { anchor.y2 = position.top; } prevPos = position; return [anchor.x1, anchor.y1, position.left, position.top, anchor.x2, anchor.y2]; }); path.push([lastPos.left, lastPos.top, lastPos.left, lastPos.top]); path.unshift(['M', firstPos.left, firstPos.top, 'C', firstPos.left, firstPos.top]); paths.push(path); }); return paths; } /** * Make spline lines path. * @param {Array.<{left: number, top: number, startTop: number}>} positions positions * @param {?object} [makeLineOptions] - options for make spline line * @param {?boolean} [makeLineOptions.connectNulls] - boolean value connect nulls or not * @param {?boolean} [makeLineOptions.isReverseDirection] - True when the line is drawn from right to left * @param {?boolean} [makeLineOptions.isBeConnected] - True when part of another line. * @returns {Array.<string | number>} paths * @private */ _makeSplineLinesPath(positions, makeLineOptions = {}) { const positionsGroups = this._getSplinePositionsGroups(positions, makeLineOptions.connectNulls); const partialPaths = this._getSplinePartialPaths(positionsGroups, makeLineOptions.isReverseDirection); let path = []; partialPaths.forEach(partialPath => { path = path.concat(partialPath); }); if (makeLineOptions.isBeConnected) { path[0] = path[0].slice(3); } return path; } /** * Render tooltip line. * @param {object} paper raphael paper * @param {number} height height * @returns {object} raphael object * @private */ _renderTooltipLine(paper, height) { const linePath = raphaelRenderUtil.makeLinePath({ left: 10, top: height }, { left: 10, top: 0 }); return raphaelRenderUtil.renderLine(paper, linePath, 'transparent', 1); } appendShadowFilterToDefs() { const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter'); const feOffset = document.createElementNS('http://www.w3.org/2000/svg', 'feOffset'); const feGaussianBlur = document.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur'); const feBlend = document.createElementNS('http://www.w3.org/2000/svg', 'feBlend'); filter.setAttributeNS(null, 'id', 'shadow'); filter.setAttributeNS(null, 'x', '-50%'); filter.setAttributeNS(null, 'y', '-50%'); filter.setAttributeNS(null, 'width', '180%'); filter.setAttributeNS(null, 'height', '180%'); feOffset.setAttributeNS(null, 'result', 'offOut'); feOffset.setAttributeNS(null, 'in', 'SourceAlpha'); feOffset.setAttributeNS(null, 'dx', '0'); feOffset.setAttributeNS(null, 'dy', '0'); feGaussianBlur.setAttributeNS(null, 'result', 'blurOut'); feGaussianBlur.setAttributeNS(null, 'in', 'offOut'); feGaussianBlur.setAttributeNS(null, 'stdDeviation', '2'); feBlend.setAttributeNS(null, 'in', 'SourceGraphic'); feBlend.setAttributeNS(null, 'in2', 'blurOut'); feBlend.setAttributeNS(null, 'mode', 'normal'); filter.appendChild(feOffset); filter.appendChild(feGaussianBlur); filter.appendChild(feBlend); this.paper.defs.appendChild(filter); } /** * Make border style. * @param {string} borderColor border color * @param {number} opacity opacity * @param {number} borderWidth border width * @returns {{stroke: string, stroke-width: number, strike-opacity: number}} border style */ makeBorderStyle(borderColor, opacity, borderWidth) { const borderStyle = { 'stroke-width': borderWidth, 'stroke-opacity': opacity }; if (borderColor) { borderStyle.stroke = borderColor; } return borderStyle; } /** * Make dot style for mouseout event. * @param {number} opacity opacity * @param {object} borderStyle border style * @returns {{fill-opacity: number, stroke-opacity: number, r: number}} style */ makeOutDotStyle(opacity, borderStyle) { const outDotStyle = { 'fill-opacity': opacity, 'stroke-opacity': opacity, r: DEFAULT_DOT_RADIUS }; if (borderStyle) { snippet.extend(outDotStyle, borderStyle); } return outDotStyle; } /** * Render dot. * @param {object} paper raphael papaer * @param {{left: number, top: number}} position dot position * @param {string} color dot color * @param {number} opacity opacity * @returns {object} raphael dot */ renderDot(paper, position, color, opacity) { const dotTheme = (this.theme && this.theme.dot) || {dot: {}}; let raphaelDot; if (position) { const dot = paper.circle( position.left, position.top, (!snippet.isUndefined(dotTheme.radius)) ? dotTheme.radius : DEFAULT_DOT_RADIUS ); const dotStyle = { fill: dotTheme.fillColor || color, 'fill-opacity': snippet.isNumber(opacity) ? opacity : dotTheme.fillOpacity, stroke: dotTheme.strokeColor || color, 'stroke-opacity': snippet.isNumber(opacity) ? opacity : dotTheme.strokeOpacity, 'stroke-width': dotTheme.strokeWidth }; dot.attr(dotStyle); raphaelDot = { dot, color }; } return raphaelDot; } /** * Move dots to front. * @param {Array.<{startDot: {dot: object}, endDot: {dot: object}}>} dots - dots * @private */ _moveDotsToFront(dots) { raphaelRenderUtil.forEach2dArray(dots, dotInfo => { dotInfo.endDot.dot.toFront(); if (dotInfo.startDot) { dotInfo.startDot.dot.toFront(); } }); } /** * Render dots. * @param {object} paper raphael paper * @param {Array.<Array.<object>>} groupPositions positions * @param {string[]} colors colors * @param {number} opacity opacity * @param {Array.<object>} [seriesSet] series set * @returns {Array.<object>} dots * @private */ _renderDots(paper, groupPositions, colors, opacity, seriesSet) { const dots = groupPositions.map((positions, groupIndex) => { const color = colors[groupIndex]; return Object.values(positions).map(position => { const dotMap = { endDot: this.renderDot(paper, position, color, opacity) }; if (this.hasRangeData) { const startPosition = snippet.extend({}, position); startPosition.top = startPosition.startTop; dotMap.startDot = this.renderDot(paper, startPosition, color, opacity); } if (seriesSet) { seriesSet.push(dotMap.endDot.dot); if (dotMap.startDot) { seriesSet.push(dotMap.startDot.dot); } } return dotMap; }); }); return dots; } /** * Get center position * @param {{left: number, top: number}} fromPos from position * @param {{left: number, top: number}} toPos to position * @returns {{left: number, top: number}} position * @private */ _getCenter(fromPos, toPos) { return { left: (fromPos.left + toPos.left) / 2, top: (fromPos.top + toPos.top) / 2 }; } /** * Show dot. * @param {object} dotInformation raphael object * @param {number} groupIndex seriesIndex * @private */ _showDot(dotInformation, groupIndex) { const hoverTheme = this.theme.dot.hover; const attributes = { 'fill-opacity': hoverTheme.fillOpacity, stroke: hoverTheme.strokeColor || dotInformation.color, 'stroke-opacity': hoverTheme.strokeOpacity, 'stroke-width': hoverTheme.strokeWidth, r: hoverTheme.radius, filter: 'url(#shadow)' }; this._setPrevDotAttributes(groupIndex, dotInformation.dot); if (hoverTheme.fillColor) { attributes.fill = hoverTheme.fillColor; } dotInformation.dot.attr(attributes); if (dotInformation.dot.node) { dotInformation.dot.node.setAttribute('filter', 'url(#shadow)'); } dotInformation.dot.toFront(); } /** * temp save dot style attribute * @param {number} groupIndex seriesIndex * @param {object} dot raphael circle object * @private */ _setPrevDotAttributes(groupIndex, dot) { if (!this._prevDotAttributes) { this._prevDotAttributes = {}; } this._prevDotAttributes[groupIndex] = dot.attr(); } /** * Update line stroke width. * @param {string} changeType over or out * @param {object} line raphael object * @private */ _updateLineStrokeOpacity(changeType, line) { let opacity = 1; const isSelectedLegend = !snippet.isNull(this.selectedLegendIndex); if (this.groupLines) { if (changeType === CHART_HOVER_STATUS_OVER || isSelectedLegend) { opacity = (this.chartType === 'radial' && this.showArea) ? 0 : DE_EMPHASIS_OPACITY; } if (changeType === CHART_HOVER_STATUS_OUT && isSelectedLegend) { line = this.getLine(this.selectedLegendIndex); } this.groupLines.forEach(otherLine => { otherLine.attr({ 'stroke-opacity': opacity }); }); line.attr({ 'stroke-opacity': 1 }); } } /** * Get the raphael line element with groupIndex * @param {number} groupIndex group index * @returns {object} line raphael object */ getLine(groupIndex) { return this.groupLines ? this.groupLines[groupIndex] : this.groupAreas[groupIndex]; } /** * Update line stroke width. * @param {string} changeType over or out * @private */ _updateAreaOpacity(changeType) { if (this.groupAreas) { this.groupAreas.forEach(otherArea => { otherArea.area.attr({ 'fill-opacity': (changeType === CHART_HOVER_STATUS_OVER) ? DE_EMPHASIS_OPACITY : 1 }); }); } } /** * Update line stroke width. * @param {object} line raphael object * @param {number} strokeWidth stroke width * @private */ _updateLineStrokeWidth(line, strokeWidth) { const changeAttr = { 'stroke-width': strokeWidth }; if (line.attrs) { changeAttr.stroke = line.attrs.stroke; } line.attr(changeAttr); } /** * Show animation. * @param {{groupIndex: number, index:number}} data show info */ showAnimation(data) { const groupIndex = data.index; const groupDot = this.groupDots[groupIndex]; const item = this._findDotItem(groupDot, data.groupIndex); let line = this.groupLines ? this.groupLines[groupIndex] : this.groupAreas[groupIndex]; let strokeWidth, startLine; if (!item) { return; } if (this.chartType === 'area') { ({startLine, line} = line); strokeWidth = 5; this._updateAreaOpacity(CHART_HOVER_STATUS_OVER); } else { strokeWidth = this.lineWidth; } this._updateLineStrokeOpacity(CHART_HOVER_STATUS_OVER, line); this._updateLineStrokeWidth(line, strokeWidth); if (startLine) { this._updateLineStrokeWidth(startLine, strokeWidth); } this._showDot(item.endDot, groupIndex); if (item.startDot) { this._showDot(item.startDot, groupIndex); } } /** * Find dot item * @param {Array.<Object>} groupDot - groupDot info * @param {number} index - dot index * @returns {Object} - raphael object * @private */ _findDotItem(groupDot = [], index) { const isRadialChart = predicate.isRadialChart(this.chartType); // For radial charts, the position path is one more than the length of the data. if (isRadialChart && groupDot.length === index) { index = 0; } return groupDot[index]; } /** * Get pivot group dots. * @returns {Array.<Array>} dots * @private */ _getPivotGroupDots() { if (!this.pivotGroupDots && this.groupDots) { this.pivotGroupDots = arrayUtil.pivot(this.groupDots); } return this.pivotGroupDots; } /** * Show group dots. * @param {number} index index * @private */ _showGroupDots(index) { const groupDots = this._getPivotGroupDots(); if (!groupDots || !groupDots[index]) { return; } groupDots[index].forEach((item, groupIndex) => { if (item.endDot) { this._showDot(item.endDot, groupIndex); } if (item.startDot) { this._showDot(item.startDot, groupIndex); } }); } /** * Show line for group tooltip. * @param {{ * dimension: {width: number, height: number}, * position: {left: number, top: number} * }} bound bound * @param {object} layout layout */ showGroupTooltipLine(bound, layout) { const left = Math.max(bound.position.left, 11); const linePath = raphaelRenderUtil.makeLinePath({ left, top: layout.position.top + bound.dimension.height }, { left, top: layout.position.top }); if (this.tooltipLine) { this.tooltipLine.attr({ path: linePath, stroke: '#999', 'stroke-opacity': 1 }); } } /** * Show group animation. * @param {number} index index */ showGroupAnimation(index) { this._showGroupDots(index); } /** * Hide dot. * @param {object} dot raphael object * @param {number} groupIndex seriesIndex * @param {?number} opacity opacity * @private */ _hideDot(dot, groupIndex, opacity) { const prev = this._prevDotAttributes[groupIndex]; let {outDotStyle} = this; // if prev data exists, use prev.r // there is dot disappearing issue, when hideDot if (prev && !snippet.isUndefined(opacity)) { outDotStyle = snippet.extend({ 'r': prev.r, 'stroke': prev.stroke, 'fill': prev.fill, 'stroke-opacity': prev['stroke-opacity'], 'stroke-width': prev['stroke-width'], 'fill-opacity': prev['fill-opacity'] }); } dot.attr(outDotStyle); if (dot.node) { dot.node.setAttribute('filter', ''); } this.resetSeriesOrder(groupIndex); } /** * Hide animation. * @param {{groupIndex: number, index:number}} data hide info */ hideAnimation(data) { const index = data.groupIndex; // Line chart has pivot values. const groupIndex = data.index; const groupDot = this.groupDots[groupIndex]; const item = this._findDotItem(groupDot, index); let line, strokeWidth, startLine; let opacity = this.dotOpacity; if (!item) { return; } line = this.groupLines ? this.groupLines[groupIndex] : this.groupAreas[groupIndex]; if (this.chartType === 'area') { strokeWidth = this.lineWidth; ({startLine, line} = line); this._updateAreaOpacity(CHART_HOVER_STATUS_OUT); } else { strokeWidth = this.lineWidth; } if (opacity && !snippet.isNull(this.selectedLegendIndex) && this.selectedLegendIndex !== groupIndex) { opacity = DE_EMPHASIS_OPACITY; } this._updateLineStrokeOpacity(CHART_HOVER_STATUS_OUT, line); this._updateLineStrokeWidth(line, strokeWidth); if (startLine) { this._updateLineStrokeWidth(startLine, strokeWidth); } if (item) { this._hideDot(item.endDot.dot, groupIndex, opacity); if (item.startDot) { this._hideDot(item.startDot.dot, groupIndex, opacity); } } } /** * Hide group dots. * @param {number} index index * @private */ _hideGroupDots(index) { const hasSelectedIndex = !snippet.isNull(this.selectedLegendIndex); const baseOpacity = this.dotOpacity; const groupDots = this._getPivotGroupDots(); if (!groupDots || !groupDots[index]) { return; } groupDots[index].forEach((item, groupIndex) => { let opacity = baseOpacity; if (opacity && hasSelectedIndex && this.selectedLegendIndex !== groupIndex) { opacity = DE_EMPHASIS_OPACITY; } if (item.endDot) { this._hideDot(item.endDot.dot, groupIndex, opacity); } if (item.startDot) { this._hideDot(item.startDot.dot, groupIndex, opacity); } }); } /** * Hide line for group tooltip. */ hideGroupTooltipLine() { this.tooltipLine.attr({ 'stroke-opacity': 0 }); } /** * Hide group animation. * @param {number} index index */ hideGroupAnimation(index) { this._hideGroupDots(index); } /** * Move dot. * @param {object} dot - raphael object * @param {{left: number, top: number}} position - position * @private */ _moveDot(dot, position) { let dotAttrs = { cx: position.left, cy: position.top }; if (this.dotOpacity) { dotAttrs = snippet.extend({'fill-opacity': this.dotOpacity}, dotAttrs, this.borderStyle); } dot.attr(dotAttrs); } /** * Animate. * @param {function} onFinish callback * @param {Array.<object>} seriesSet series set */ animate(onFinish, seriesSet) { const {paper, dimension, position} = this; const clipRectId = this._getClipRectId(); const remakePosition = this._makeClipRectPosition(position); let {clipRect} = this; if (!IS_LTE_IE8 && dimension) { if (!clipRect) { clipRect = createClipPathRectWithLayout(paper, remakePosition, dimension, clipRectId); this.clipRect = clipRect; } else { this._makeClipRectPosition(position); clipRect.attr({ width: 0, height: dimension.height, x: remakePosition.left, y: remakePosition.top }); } seriesSet.forEach(seriesElement => { seriesElement.node.setAttribute('clip-path', `url(#${clipRectId})`); }); clipRect.animate({ width: dimension.width }, ANIMATION_DURATION, '>', onFinish); } } /** * Make selection dot. * @param {object} position clip rect position * @param {number} left clip rect left position * @param {number} top clip rect top position * @returns {{top: number, left: number}} remake clip rect position * @private */ _makeClipRectPosition(position) { return { left: position.left - chartConst.SERIES_EXPAND_SIZE, top: position.top - chartConst.SERIES_EXPAND_SIZE }; } /** * Make selection dot. * @param {object} paper raphael paper * @returns {object} selection dot * @private */ _makeSelectionDot(paper) { const selectionDot = paper.circle(0, 0, SELECTION_DOT_RADIUS); selectionDot.attr({ 'fill': '#ffffff', 'fill-opacity': 0, 'stroke-opacity': 0, 'stroke-width': 2 }); return selectionDot; } /** * Select series. * @param {{groupIndex: number, index: number}} indexes indexes */ selectSeries(indexes) { const item = this.groupDots[indexes.index][indexes.groupIndex]; const position = this.groupPositions[indexes.index][indexes.groupIndex]; this.selectedItem = item; this.selectionDot.attr({ cx: position.left, cy: position.top, 'fill-opacity': 0.5, 'stroke-opacity': 1, stroke: this.selectionColor || item.endDot.color }); if (this.selectionStartDot) { this.selectionStartDot.attr({ cx: position.left, cy: position.startTop, 'fill-opacity': 0.5, 'stroke-opacity': 1, stroke: this.selectionColor || item.startDot.color }); } } /** * Unselect series. * @param {{groupIndex: number, index: number}} indexes indexes */ unselectSeries(indexes) { const item = this.groupDots[indexes.index][indexes.groupIndex]; if (this.selectedItem === item) { this.selectionDot.attr({ 'fill-opacity': 0, 'stroke-opacity': 0 }); } if (this.selectionStartDot) { this.selectionStartDot.attr({ 'fill-opacity': 0, 'stroke-opacity': 0 }); } } /** * Set width or height of paper. * @param {number} width - width * @param {number} height - height */ setSize(width, height) { width = width || this.dimension.width; height = height || this.dimension.height; this.paper.setSize(width, height); } /** * Animate by position. * @param {object} raphaelObj - raphael object * @param {{left: number, top: number}} position - position * @param {number} tickSize tick size * @private */ _animateByPosition(raphaelObj, position, tickSize) { const attr = { cx: position.left, cy: position.top }; if (snippet.isExisty(tickSize)) { attr.transform = `t-${tickSize},0`; } raphaelObj.animate(attr, MOVING_ANIMATION_DURATION); } /** * Animate by path. * @param {object} raphaelObj - raphael object * @param {Array.<string | number>} paths - paths * @param {number} tickSize tick size * @private */ _animateByPath(raphaelObj, paths, tickSize) { const attr = { path: paths.join(' ') }; if (snippet.isExisty(tickSize)) { attr.transform = `t-${tickSize},0`; } raphaelObj.animate(attr, MOVING_ANIMATION_DURATION); } /** * Remove first dot. * @param {Array.<object>} dots - dots * @private */ _removeFirstDot(dots) { const firstDot = dots.shift(); firstDot.endDot.dot.remove(); if (firstDot.startDot) { firstDot.startDot.dot.remove(); } } /** * Clear paper. */ clear() { delete this.paper.dots; this.paper.clear(); } /** * Resize clip rect size * @param {number} width series width * @param {number} height series height */ resizeClipRect(width, height) { const clipRect = this.paper.getById(`${this._getClipRectId()}_rect`); clipRect.attr({ width, height }); } /** * Set clip rect id * @returns {string} id - clip rect id * @private */ _getClipRectId() { if (!this.clipRectId) { this.clipRectId = renderUtil.generateClipRectId(); } return this.clipRectId; } /** * Reset series order after selected to be same to when it is first rendered * @param {number} legendIndex - legend index to reset series order * @ignore * @abstract */ resetSeriesOrder() {} /** * @param {SVGElement | {area: {SVGElement}, line: {SVGElement}, startLine: {SVGElement}}} lineType - line or area graph * @param {Array.<SVGElement>} dots - dot type element * @abstract */ moveSeriesToFront() {} } /** * Create clip rect with layout * @param {object} paper Raphael paper * @param {object} position position * @param {object} dimension dimension * @param {string} id ID string * @returns {object} * @ignore */ function createClipPathRectWithLayout(paper, position, dimension, id) { const clipPath = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath'); const rect = paper.rect(position.left, position.top, 0, dimension.height); rect.id = `${id}_rect`; clipPath.id = id; clipPath.appendChild(rect.node); paper.defs.appendChild(clipPath); return rect; } export default RaphaelLineTypeBase;
var x = "4"; export var result = `56 = ${x}`;
module.exports = function (platform) { var writable = require('./writable.js'); var sharedDiscover = require('./discover.js'); var sharedFetch = require('./fetch.js'); var pushToPull = require('push-to-pull'); var pktLine = require('./pkt-line.js')(platform); var framer = pushToPull(pktLine.framer); var deframer = pushToPull(pktLine.deframer); var http = platform.http; var trace = platform.trace; var bops = platform.bops; var agent = platform.agent; var urlParse = require('./url-parse.js'); // opts.hostname - host to connect to (github.com) // opts.pathname - path to repo (/creationix/conquest.git) // opts.port - override default port (80 for http, 443 for https) return function (opts) { opts.tls = opts.protocol === "https:"; opts.port = opts.port ? opts.port | 0 : (opts.tls ? 443 : 80); if (!opts.hostname) throw new TypeError("hostname is a required option"); if (!opts.pathname) throw new TypeError("pathname is a required option"); opts.discover = discover; opts.fetch = fetch; opts.close = closeConnection; var write, read, abort, cb, error, pathname, headers; return opts; function connect() { write = writable(); var output = write; if (trace) output = trace("output", output); output = framer(output); read = null; abort = null; post(pathname, headers, output, onResponse); } function onResponse(err, code, headers, body) { if (err) return onError(err); if (code !== 200) return onError(new Error("Unexpected status code " + code)); if (headers['content-type'] !== 'application/x-git-upload-pack-result') { return onError(new Error("Wrong content-type in server response")); } body = deframer(body); if (trace) body = trace("input", body); read = body.read; abort = body.abort; if (cb) { var callback = cb; cb = null; return read(callback); } } function onError(err) { if (cb) { var callback = cb; cb = null; return callback(err); } error = err; } function enqueue(callback) { if (error) { var err = error; error = null; return callback(err); } cb = callback; } function addDefaults(extras) { var headers = { "User-Agent": agent, "Host": opts.hostname, }; // Hack to workaround gist bug. // https://github.com/creationix/js-git/issues/25 if (opts.hostname === "gist.github.com") { headers["User-Agent"] = "git/1.8.1.2"; headers["X-Real-User-Agent"] = agent; } for (var key in extras) { headers[key] = extras[key]; } return headers; } function get(path, headers, callback) { return http.request({ method: "GET", hostname: opts.hostname, tls: opts.tls, port: opts.port, auth: opts.auth, path: opts.pathname + path, headers: addDefaults(headers) }, onGet); function onGet(err, code, responseHeaders, body) { if (err) return callback(err); if (code === 301) { var uri = urlParse(responseHeaders.location); opts.protocol = uri.protocol; opts.hostname = uri.hostname; opts.tls = uri.protocol === "https:"; opts.port = uri.port; opts.auth = uri.auth; opts.pathname = uri.path.replace(path, ""); return get(path, headers, callback); } return callback(err, code, responseHeaders, body); } } function buffer(body, callback) { var parts = []; body.read(onRead); function onRead(err, item) { if (err) return callback(err); if (item === undefined) { return callback(null, bops.join(parts)); } parts.push(item); body.read(onRead); } } function post(path, headers, body, callback) { headers = addDefaults(headers); if (typeof body === "string") { body = bops.from(body); } if (bops.is(body)) { headers["Content-Length"] = body.length; } else { if (headers['Transfer-Encoding'] !== 'chunked') { return buffer(body, function (err, body) { if (err) return callback(err); headers["Content-Length"] = body.length; send(body); }); } } send(body); function send(body) { http.request({ method: "POST", hostname: opts.hostname, tls: opts.tls, port: opts.port, auth: opts.auth, path: opts.pathname + path, headers: headers, body: body }, callback); } } // Send initial git-upload-pack request // outputs refs and caps function discover(callback) { if (!callback) return discover.bind(this); get("/info/refs?service=git-upload-pack", { "Accept": "*/*", "Accept-Encoding": "gzip", "Pragma": "no-cache" }, function (err, code, headers, body) { if (err) return callback(err); if (code !== 200) return callback(new Error("Unexpected status code " + code)); if (headers['content-type'] !== 'application/x-git-upload-pack-advertisement') { return callback(new Error("Wrong content-type in server response")); } body = deframer(body); if (trace) body = trace("input", body); body.read(function (err, line) { if (err) return callback(err); if (line.trim() !== '# service=git-upload-pack') { return callback(new Error("Missing expected service line")); } body.read(function (err, line) { if (err) return callback(err); if (line !== null) { return callback(new Error("Missing expected terminator")); } sharedDiscover(body, callback); }); }); }); } function fetch(repo, opts, callback) { if (!callback) return fetch.bind(this, repo, opts); pathname = "/git-upload-pack"; headers = { "Content-Type": "application/x-git-upload-pack-request", "Accept": "application/x-git-upload-pack-result", }; return sharedFetch({ read: resRead, abort: resAbort, write: resWrite }, repo, opts, callback); } function resRead(callback) { if (read) return read(callback); return enqueue(callback); } function resAbort(callback) { if (abort) return abort(callback); return callback(); } function resWrite(line) { if (!write) connect(); if (line === "done\n") { write(line); write(); write = null; } else { write(line); } } function closeConnection(callback) { if (!callback) return closeConnection.bind(this); callback(); } }; };
var express = require('express'); var app = express(); app.set('port', process.env.PORT || 3000); //<co id="callout-config-1-1" /> app.configure('development', function() { //<co id="callout-config-1-2" /> app.set('db', 'localhost/development'); }); app.configure('production', function() { //<co id="callout-config-1-3" /> app.set('db', 'db.example.com/production'); }); app.listen(app.get('port'), function() { //<co id="callout-config-1-4" /> console.log('Using database:', app.get('db')); console.log('Listening on port:', app.get('port')); });
var glob = require('glob'); var path = require('path'); function loadTasks(gulp, plugins, paths) { var taskNames = []; // Load all tasks from tasks folder glob.sync(path.resolve(__dirname, '../tasks/*.js')).forEach(function(filePath) { var taskName = path.basename(filePath, '.js'); taskNames.push(taskName); var task = require(filePath).task; var deps = require(filePath).deps || []; gulp.task(taskName, deps, function() { task(gulp, plugins, paths) }); }); return taskNames; } module.exports.loadTasks = loadTasks;
/* Get Programming with JavaScript * Listing 10.01 * Bracket notation for object properties */ var ages = {}; ages["Kandra"] = 56; ages["Dax"] = 21; console.log(ages.Kandra); console.log(ages.Dax); /* Further Adventures * * 1) Add a couple more properties to * the ages object. * * 2) Change the calls to console.log * to use square bracket notation as well. * */
// Generated by CoffeeScript 1.6.2 (function() { var workspace, workspaceViewModel, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.SingleExecutionViewModel = kb.ViewModel.extend({ constructor: function(model, options) { return kb.ViewModel.prototype.constructor.call(this, model, {}, options); } }); window.SingleExecutionCollection = kb.CollectionObservable.extend({ constructor: function(collection, options) { return kb.CollectionObservable.prototype.constructor.call(this, collection, { view_model: SingleExecutionViewModel, options: options }); } }); window.WorkspaceViewModel = kb.ViewModel.extend({ constructor: function(model, options) { kb.ViewModel.prototype.constructor.call(this, model, { requires: ['singleExecutions'], factories: { 'singleExecutions': SingleExecutionCollection } }, options); console.log("calling workspace view model"); }, init: function() { return this.subscribeEvents(); }, subscribeEvents: function() { var _this = this; return this.singleExecutions.subscribe(function(executionViewModels) { return alert(executionViewModels); }); } }); window.Workspace1 = (function(_super) { __extends(Workspace1, _super); Workspace1.prototype.defaults = { singleExecutions: new Backbone.Collection(), batchExecutions: new Backbone.Collection() }; function Workspace1() { Workspace1.__super__.constructor.call(this); } return Workspace1; })(Backbone.Model); workspace = new Workspace1(); workspaceViewModel = new WorkspaceViewModel(workspace); workspaceViewModel.init(); workspace.get('singleExecutions').add(new Backbone.Model()); }).call(this);
import {Spinner} from "../spin.js"; var inputs = document.querySelectorAll('input[min], select'); var cbInputs = document.querySelectorAll('input[type="checkbox"]'); var spinnerEl = document.getElementById('preview'); var spinner; for (var i = 0; i < inputs.length; i++) { inputs[i].addEventListener('change', update); } for (var i = 0; i < cbInputs.length; i++) { cbInputs[i].addEventListener('click', update); } update(); function update () { var opts = {color: '#fff'}; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; opts[input.name] = parseFloat(input.value); } for (var i = 0; i < cbInputs.length; i++) { var input = cbInputs[i]; opts[input.name] = input.checked; } if (spinner) { spinner.stop(); } spinner = new Spinner(opts).spin(spinnerEl); }
import {Transform} from "../transform" // ;; A selection-aware extension of `Transform`. Use // `ProseMirror.tr` to create an instance. export class EditorTransform extends Transform { constructor(pm) { super(pm.doc) this.pm = pm } // :: (?Object) → ?EditorTransform // Apply the transformation. Returns the transform, or `false` it is // was empty. apply(options) { return this.pm.apply(this, options) } // :: Selection // Get the editor's current selection, [mapped](#Selection.map) // through the steps in this transform. get selection() { return this.steps.length ? this.pm.selection.map(this) : this.pm.selection } // :: (?Node, ?bool) → EditorTransform // Replace the selection with the given node, or delete it if `node` // is null. When `inheritMarks` is true and the node is an inline // node, it inherits the marks from the place where it is inserted. replaceSelection(node, inheritMarks) { let {empty, from, to, node: selNode} = this.selection if (node && node.isInline && inheritMarks !== false) node = node.mark(empty ? this.pm.input.storedMarks : this.doc.marksAt(from)) if (selNode && selNode.isTextblock && node && node.isInline) { // Putting inline stuff onto a selected textblock puts it // inside, so cut off the sides from++ to-- } else if (selNode) { // This node can not simply be removed/replaced. Remove its parent as well let $from = this.doc.resolve(from), depth = $from.depth while (depth && $from.node(depth).childCount == 1 && !(node ? $from.node(depth).type.canContain(node) : $from.node(depth).type.canBeEmpty)) depth-- if (depth < $from.depth) { from = $from.before(depth + 1) to = $from.after(depth + 1) } } else if (node && node.isBlock) { let $from = this.doc.resolve(from) // Inserting a block node into a textblock. Try to insert it above by splitting the textblock if ($from.depth && $from.node($from.depth - 1).type.canContain(node)) { this.delete(from, to) if ($from.parentOffset && $from.parentOffset < $from.parent.content.size) this.split(from) return this.insert(from + ($from.parentOffset ? 1 : -1), node) } } return this.replaceWith(from, to, node) } // :: () → EditorTransform // Delete the selection. deleteSelection() { return this.replaceSelection() } // :: (string) → EditorTransform // Replace the selection with a text node containing the given string. typeText(text) { return this.replaceSelection(this.pm.schema.text(text), true) } }
module.exports = function(app){ var index = require('../controllers/index.server.controller'); app.get('/', index.render); };
var DistancePower = function (x1, y1, x2, y2, pow) { if (pow === undefined) { pow = 2; } return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow)); }; module.exports = DistancePower;
define({ "showLayerLabels": "عرض أسماء الطبقة", "autoPlay": "تشغيل شريط التمرير تلقائيًا", "loopPlay": "تكرار الوقت باستمرار", "dateAndTimeFormat": "تنسيق التاريخ والوقت", "mapDefault": "الوضع الافتراضي للخريطة", "custom": "تخصيص", "formatInstruction": "تعليمات التنسيق", "playback": "تشغيل الموضع الذي تم حفظه في الخريطة", "MMMMYYYY": "يوليو 2015", "MMMYYYY": "يوليو 2015", "MMMMDYYYY": "يوليو 21,2015", "dddMMMDDYYYY": "الثلاثاء يوليو 21، 2015", "MDDYYYY": "7/21/2015", "YYYYMDD": "2015/7/21", "MDDYY": "7/21/2015", "YYYY": "2015", "MDDYYYYhmma": "7/21/2015 8:00 ص", "dddMMMDDhmma": "الثلاثاء يوليو 21 8:00 ص", "sliderSetting": "إعدادات شريط التمرير", "autoRefresh": "تحديث شريط التمرير كل", "timeSetting": "إعدادات الوقت", "useWebMapSetting": "تنفيذ إعدادات الوقت لخريطة الويب", "useConfigureSetting": "تكوين إعدادات الوقت", "timeSettingBtn": "إعداد", "calenderError": "يجب أن يكون وقت البداية أصغر من وقت النهاية.", "timeSpan": "الزمني", "startTime": "وقت البدء", "endTime": "وقت الانتهاء", "unit": "وحدة", "timeDisplay": "الوقت", "displayDataIn": "عرض البيانات في", "interval": "فاصل", "displayAllData": "عرض كل البيانات تدريجيًا", "layerTimeExtent": "تمكين الرسوم المتحركة للوقت", "layerTableCol1": "طبقة", "layerTableCol2": "نطاق الوقت", "timeTo": "إلى", "calender": "التقويم", "time": "الوقت", "now": "الآن", "today": "اليوم", "maximum": "الحد الأقصى لكل المُحدد", "minimum": "الحد الأدنى لكل المُحدد" });
import test from 'tape'; import proc from '../../src/internal/proc' import { is, deferred, arrayOfDeffered } from '../../src/utils' import * as io from '../../src/effects' test('proc fork handling: generators', assert => { assert.plan(4); let task, task2; function* subGen(arg) { yield Promise.resolve(1) return arg } class C { constructor(val) { this.val = val } *gen() { return this.val } } const inst = new C(2) function* genFn() { task = yield io.fork(subGen, 1) task2 = yield io.fork([inst, inst.gen]) } proc(genFn()).done.catch(err => assert.fail(err)) setTimeout(() => { assert.equal(task.name, 'subGen', 'fork result must include the name of the forked generator function' ), assert.equal(is.promise(task.done), true, 'fork result must include the promise of the task result' ), task.done.then(res => assert.equal(res, 1, 'fork result must resolve with the return value of the forked task' )) task2.done.then(res => assert.equal(res, 2, 'fork must also handle generators defined as instance methods' )) }, 0) }); test('proc join handling : generators', assert => { assert.plan(1); let actual = []; const defs = arrayOfDeffered(2) const input = cb => { Promise.resolve(1) .then(() => defs[0].resolve(true)) .then(() => cb({type: 'action-1'})) .then(() => defs[1].resolve(2)) // the result of the fork will be resolved the last // proc must not block and miss the 2 precedent effects return () => {} } function* subGen(arg) { yield defs[1].promise // will be resolved after the action-1 return arg } function* genFn() { const task = yield io.fork(subGen, 1) actual.push( yield defs[0].promise ) actual.push( yield io.take('action-1') ) actual.push( yield io.join(task) ) } proc(genFn(), input).done.catch(err => assert.fail(err)) const expected = [true, {type: 'action-1'}, 1] setTimeout(() => { assert.deepEqual(actual, expected, 'proc must not block on forked tasks, but block on joined tasks' ) }, 0) }); test('proc fork/join handling : functions', assert => { assert.plan(1); let actual = []; const defs = arrayOfDeffered(2) Promise.resolve(1) .then(() => defs[0].resolve(true)) .then(() => defs[1].resolve(2)) function api() { return defs[1].promise } function syncFn() { return 'sync' } function* genFn() { const task = yield io.fork(api) const syncTask = yield io.fork(syncFn) actual.push( yield defs[0].promise ) actual.push( yield io.join(task) ) actual.push( yield io.join(syncTask) ) } proc(genFn()).done.catch(err => assert.fail(err)) const expected = [true, 2, 'sync'] setTimeout(() => { assert.deepEqual(actual, expected, 'proc must not block on forked tasks, but block on joined tasks' ) }, 0) }); test('proc fork wait for attached children', assert => { assert.plan(1) const actual = [] const rootDef = deferred() const childAdef = deferred() const childBdef = deferred() const defs = arrayOfDeffered(4) Promise.resolve() .then(childAdef.resolve) .then(rootDef.resolve) .then(defs[0].resolve) .then(childBdef.resolve) .then(defs[2].resolve) .then(defs[3].resolve) .then(defs[1].resolve) function* root() { yield io.fork(childA) yield rootDef.promise yield io.fork(childB) } function* childA() { yield io.fork(leaf, 0) yield childAdef.promise yield io.fork(leaf, 1) } function* childB() { yield io.fork(leaf, 2) yield childBdef.promise yield io.fork(leaf, 3) } function* leaf(idx) { yield defs[idx].promise actual.push(idx) } proc(root()).done.then(() => { assert.deepEqual(actual, [0,2,3,1], 'parent task must wait for all forked tasks before terminating') }).catch(err => assert.fail(err)) }) test('proc auto cancel forks on error', assert => { assert.plan(1) const actual = [] const mainDef = deferred() const childAdef = deferred() const childBdef = deferred() const defs = arrayOfDeffered(4) Promise.resolve() .then(() => childAdef.resolve('childA resolved')) .then(() => defs[0].resolve('leaf 1 resolved')) .then(() => childBdef.resolve('childB resolved')) .then(() => defs[1].resolve('leaf 2 resolved')) .then(() => mainDef.reject('main error')) // .then(() => defs[2].resolve('leaf 3 resolved')) .then(() => defs[3].resolve('leaf 4 resolved')) function* root() { try { actual.push( yield io.call(main) ) } catch(e) { actual.push('root caught ' + e) } } function* main() { try { yield io.fork(childA) yield io.fork(childB) actual.push( yield mainDef.promise ) } catch (e) { actual.push(e) throw e } finally { if(yield io.cancelled()) actual.push('main cancelled') } } function* childA() { try { yield io.fork(leaf, 0) actual.push( yield childAdef.promise ) yield io.fork(leaf, 1) } finally { if(yield io.cancelled()) actual.push('childA cancelled') } } function* childB() { try { yield io.fork(leaf, 2) yield io.fork(leaf, 3) actual.push( yield childBdef.promise ) } finally { if(yield io.cancelled()) actual.push('childB cancelled') } } function* leaf(idx) { try { actual.push( yield defs[idx].promise ) } finally { if(yield io.cancelled()) actual.push(`leaf ${idx+1} cancelled`) } } const expected = [ 'childA resolved', 'leaf 1 resolved', 'childB resolved', 'leaf 2 resolved', 'main error', 'leaf 3 cancelled', 'leaf 4 cancelled', 'root caught main error' ] proc(root()).done.then(() => { assert.deepEqual(actual, expected, 'parent task must cancel all forked tasks when it aborts') }).catch(err => assert.fail(err)) }) test('proc auto cancel forks on main cancelled', assert => { assert.plan(1) const actual = [] const rootDef = deferred() const mainDef = deferred() const childAdef = deferred() const childBdef = deferred() const defs = arrayOfDeffered(4) Promise.resolve() .then(() => childAdef.resolve('childA resolved')) .then(() => defs[0].resolve('leaf 1 resolved')) .then(() => childBdef.resolve('childB resolved')) .then(() => defs[1].resolve('leaf 2 resolved')) .then(() => rootDef.resolve('root resolved')) //.then(() => new Promise(r => setTimeout(r,0))) .then(() => mainDef.resolve('main resolved')) .then(() => defs[2].resolve('leaf 3 resolved')) .then(() => defs[3].resolve('leaf 4 resolved')) function* root() { try { const task = yield io.fork(main) actual.push( yield rootDef.promise ) yield io.cancel(task) } catch (e) { actual.push('root caught ' + e) } } function* main() { try { yield io.fork(childA) yield io.fork(childB) actual.push( yield mainDef.promise ) } finally { if(yield io.cancelled()) actual.push('main cancelled') } } function* childA() { try { yield io.fork(leaf, 0) actual.push( yield childAdef.promise ) yield io.fork(leaf, 1) } finally { if(yield io.cancelled()) actual.push('childA cancelled') } } function* childB() { try { yield io.fork(leaf, 2) yield io.fork(leaf, 3) actual.push( yield childBdef.promise ) } finally { if(yield io.cancelled()) actual.push('childB cancelled') } } function* leaf(idx) { try { actual.push( yield defs[idx].promise ) } finally { if(yield io.cancelled()) actual.push(`leaf ${idx+1} cancelled`) } } const expected = [ 'childA resolved', 'leaf 1 resolved', 'childB resolved', 'leaf 2 resolved', 'root resolved', 'main cancelled', 'leaf 3 cancelled', 'leaf 4 cancelled' ] proc(root()).done.then(() => { assert.deepEqual(actual, expected, 'parent task must cancel all forked tasks when it\'s cancelled') }).catch(err => assert.fail(err)) }) test('proc auto cancel forks if a child aborts', assert => { assert.plan(1) const actual = [] /* const _push = actual.push actual.push = (arg) => { console.log(arg) _push.call(actual, arg) } */ const mainDef = deferred() const childAdef = deferred() const childBdef = deferred() const defs = arrayOfDeffered(4) Promise.resolve() .then(() => childAdef.resolve('childA resolved')) .then(() => defs[0].resolve('leaf 1 resolved')) .then(() => childBdef.resolve('childB resolved')) .then(() => defs[1].resolve('leaf 2 resolved')) .then(() => mainDef.resolve('main resolved')) .then(() => defs[2].reject('leaf 3 error')) .then(() => defs[3].resolve('leaf 4 resolved')) function* root() { try { actual.push( yield io.call(main) ) } catch (e) { actual.push('root caught ' + e) } } function* main() { try { yield io.fork(childA) yield io.fork(childB) actual.push( yield mainDef.promise ) return 'main returned' } finally { if(yield io.cancelled()) actual.push('main cancelled') } } function* childA() { try { yield io.fork(leaf, 0) actual.push( yield childAdef.promise ) yield io.fork(leaf, 1) } finally { if(yield io.cancelled()) actual.push('childA cancelled') } } function* childB() { try { yield io.fork(leaf, 2) yield io.fork(leaf, 3) actual.push( yield childBdef.promise ) } finally { if(yield io.cancelled()) actual.push('childB cancelled') } } function* leaf(idx) { try { actual.push( yield defs[idx].promise ) } catch (e) { actual.push(e) throw e } finally { if(yield io.cancelled()) actual.push(`leaf ${idx+1} cancelled`) } } const expected = [ 'childA resolved', 'leaf 1 resolved', 'childB resolved', 'leaf 2 resolved', 'main resolved', 'leaf 3 error', 'leaf 4 cancelled', 'root caught leaf 3 error' ] proc(root()).done.then(() => { assert.deepEqual(actual, expected, 'parent task must cancel all forked tasks when it aborts') }).catch(err => assert.fail(err)) }) test('proc auto cancel parent + forks if a child aborts', assert => { assert.plan(1) const actual = [] /* const _push = actual.push actual.push = (arg) => { console.log(arg) _push.call(actual, arg) } */ const mainDef = deferred() const childAdef = deferred() const childBdef = deferred() const defs = arrayOfDeffered(4) Promise.resolve() .then(() => childAdef.resolve('childA resolved')) .then(() => defs[0].resolve('leaf 1 resolved')) .then(() => childBdef.resolve('childB resolved')) .then(() => defs[1].resolve('leaf 2 resolved')) .then(() => defs[2].reject('leaf 3 error')) .then(() => mainDef.resolve('main resolved')) .then(() => defs[3].resolve('leaf 4 resolved')) function* root() { try { actual.push( yield io.call(main) ) } catch (e) { actual.push('root caught ' + e) } } function* main() { try { yield io.fork(childA) yield io.fork(childB) actual.push( yield mainDef.promise ) return 'main returned' } catch (e) { actual.push(e) throw e } finally { if(yield io.cancelled()) actual.push('main cancelled') } } function* childA() { try { yield io.fork(leaf, 0) actual.push( yield childAdef.promise ) yield io.fork(leaf, 1) } finally { if(yield io.cancelled()) actual.push('childA cancelled') } } function* childB() { try { yield io.fork(leaf, 2) yield io.fork(leaf, 3) actual.push( yield childBdef.promise ) } finally { if(yield io.cancelled()) actual.push('childB cancelled') } } function* leaf(idx) { try { actual.push( yield defs[idx].promise ) } catch (e) { actual.push(e) throw e } finally { if(yield io.cancelled()) actual.push(`leaf ${idx+1} cancelled`) } } const expected = [ 'childA resolved', 'leaf 1 resolved', 'childB resolved', 'leaf 2 resolved', 'leaf 3 error', 'leaf 4 cancelled', 'main cancelled', 'root caught leaf 3 error' ] proc(root()).done.then(() => { assert.deepEqual(actual, expected, 'parent task must cancel all forked tasks when it aborts') }).catch(err => assert.fail(err)) })
import React from 'react'; import { FormPanel, PasswordField } from '@extjs/ext-react'; export default function PasswordFieldExample() { return ( <FormPanel shadow> <PasswordField width={200} label="Password" required revealable /> </FormPanel> ) }
var R = require('../..'); var objs = [ {x: [1, 2], y: true}, {x: [1, 3], y: true}, {x: [], y: false}, {x: [2], y: false}, {x: [3], y: true}, {x: [1], y: true}, {x: [1, 2, 3], y: true}, {x: [], y: true}, {x: [1, 2], y: false}, {x: [1, 3], y: true} ]; var findEmptyX = R.find(R.where({x: R.isEmpty})); var findFalseY = R.find(R.whereEq({y: false})); module.exports = { name: 'find where', tests: { 'find(where({x: isEmpty}), objs)': function() { R.find(R.where({x: R.isEmpty}), objs); }, 'find(where({x: isEmpty}))(objs)': function() { R.find(R.where({x: R.isEmpty}))(objs); }, 'findEmptyX(objs)': function() { findEmptyX(objs); }, 'find(whereEq({y: false}), objs)': function() { R.find(R.whereEq({y: false}), objs); }, 'find(whereEq({y: false}))(objs)': function() { R.find(R.whereEq({y: false}))(objs); }, 'findFalseY(objs)': function() { findFalseY(objs); } } };
define( function (require) { var lang = require('common/lang'); describe('测试overwrite', function () { it('test normal object', function () { var result = lang.overwrite( { x: 1 }, { x: 2 } ); expect(result.x).toBe(2); }); it('test null object', function () { var result = lang.overwrite( { x: 1 }, null ); expect(result.x).toBe(1); var result = lang.overwrite( { x: 1 }, undefined ); expect(result.x).toBe(1); var result = lang.overwrite( { x: 1 }, false ); expect(result.x).toBe(1); }); it('test fields', function () { var result = lang.overwrite( { x: 1 }, { x: 2 }, ['x'] ); expect(result.x).toBe(2); var result = lang.overwrite( { x: 1 }, { x: 2 }, ['y'] ); expect(result.x).toBe(1); }); it('test deep overwrite', function () { var result = lang.overwrite( { level1: { x: 1 } }, { level1: { y: 3 } } ); expect(result.level1.y).toBe(3); var result = lang.overwrite( { level1: { x: 1 } }, { level1: { x: 2 } } ); expect(result.level1.x).toBe(2); }); it('test null overwrite', function () { var result = lang.overwrite( { level1: { x: 1 } }, { level1: { x: null } } ); expect(result.level1.x).toBeNull(); }); it('test string overwrite', function () { var result = lang.overwrite( 'abcde', { 0: 'f' } ); expect(result['0']).toBe('a'); }); }); describe('测试equals', function () { it('test normal object', function () { var result = lang.equals( { x: 1 }, { x: 2 } ); expect(result).toBeFalsy(); var result = lang.equals( { x: null }, { x: undefined } ); expect(result).toBeFalsy(); var result = lang.equals( { x: 1 }, { x: '1' } ); expect(result).toBeFalsy(); }); it('test basic type', function () { var result = lang.equals( null, undefined ); expect(result).toBeTruthy(); var result = lang.equals( 1, 2 ); expect(result).toBeFalsy(); var result = lang.equals( 1, '1' ); expect(result).toBeFalsy(); }); it('test deep equals', function () { var result = lang.equals( { level1: { x: 1 } }, { level1: { y: 1 } } ); expect(result).toBeFalsy(); var result = lang.equals( { level1: { x: 1 } }, { level1: { x: 1 } } ); expect(result).toBeTruthy(); }); }); } );
/*! jQuery UI - v1.10.4 - 2014-06-07 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.ka={closeText:"დახურვა",prevText:"&#x3c; წინა",nextText:"შემდეგი &#x3e;",currentText:"დღეს",monthNames:["იანვარი","თებერვალი","მარტი","აპრილი","მაისი","ივნისი","ივლისი","აგვისტო","სექტემბერი","ოქტომბერი","ნოემბერი","დეკემბერი"],monthNamesShort:["იან","თებ","მარ","აპრ","მაი","ივნ","ივლ","აგვ","სექ","ოქტ","ნოე","დეკ"],dayNames:["კვირა","ორშაბათი","სამშაბათი","ოთხშაბათი","ხუთშაბათი","პარასკევი","შაბათი"],dayNamesShort:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],dayNamesMin:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],weekHeader:"კვირა",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.ka)});
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.GrabLineLinked = void 0; var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var GrabLineLinked = function GrabLineLinked() { (0, _classCallCheck2["default"])(this, GrabLineLinked); this.opacity = void 0; this.opacity = 1; }; exports.GrabLineLinked = GrabLineLinked; //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9DbGFzc2VzL09wdGlvbnMvSW50ZXJhY3Rpdml0eS9Nb2Rlcy9HcmFiTGluZUxpbmtlZC50cyJdLCJuYW1lcyI6WyJHcmFiTGluZUxpbmtlZCIsIm9wYWNpdHkiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7O0lBRWFBLGMsR0FHVCwwQkFBYztBQUFBO0FBQUEsT0FGUEMsT0FFTztBQUNWLE9BQUtBLE9BQUwsR0FBZSxDQUFmO0FBQ0gsQyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7SUdyYWJMaW5lTGlua2VkfSBmcm9tIFwiLi4vLi4vLi4vLi4vSW50ZXJmYWNlcy9PcHRpb25zL0ludGVyYWN0aXZpdHkvTW9kZXMvSUdyYWJMaW5lTGlua2VkXCI7XG5cbmV4cG9ydCBjbGFzcyBHcmFiTGluZUxpbmtlZCBpbXBsZW1lbnRzIElHcmFiTGluZUxpbmtlZCB7XG4gICAgcHVibGljIG9wYWNpdHk6IG51bWJlcjtcblxuICAgIGNvbnN0cnVjdG9yKCkge1xuICAgICAgICB0aGlzLm9wYWNpdHkgPSAxO1xuICAgIH1cbn1cbiJdfQ==
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); const TEXT_NODE_TYPE = 3; let React; let ReactDOM; let ReactDOMServer; function initModules() { jest.resetModuleRegistry(); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); // Make them available to the helpers. return { ReactDOM, ReactDOMServer, }; } const { resetModules, itRenders, itThrowsWhenRendering, serverRender, streamRender, clientCleanRender, clientRenderOnServerString, } = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('elements and children', function() { function expectNode(node, type, value) { expect(node).not.toBe(null); expect(node.nodeType).toBe(type); expect(node.nodeValue).toMatch(value); } function expectTextNode(node, text) { expectNode(node, TEXT_NODE_TYPE, text); } describe('text children', function() { itRenders('a div with text', async render => { const e = await render(<div>Text</div>); expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a div with text with flanking whitespace', async render => { // prettier-ignore const e = await render(<div> Text </div>); expect(e.childNodes.length).toBe(1); expectNode(e.childNodes[0], TEXT_NODE_TYPE, ' Text '); }); itRenders('a div with an empty text child', async render => { const e = await render(<div>{''}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('a div with multiple empty text children', async render => { const e = await render( <div> {''} {''} {''} </div>, ); if (render === serverRender || render === streamRender) { // For plain server markup result we should have no text nodes if // they're all empty. expect(e.childNodes.length).toBe(0); expect(e.textContent).toBe(''); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], ''); expectTextNode(e.childNodes[1], ''); expectTextNode(e.childNodes[2], ''); } }); itRenders('a div with multiple whitespace children', async render => { // prettier-ignore const e = await render(<div>{' '}{' '}{' '}</div>); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // For plain server markup result we have comments between. // If we're able to hydrate, they remain. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], ' '); expectTextNode(e.childNodes[2], ' '); expectTextNode(e.childNodes[4], ' '); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], ' '); expectTextNode(e.childNodes[1], ' '); expectTextNode(e.childNodes[2], ' '); } }); itRenders('a div with text sibling to a node', async render => { const e = await render( <div> Text<span>More Text</span> </div>, ); let spanNode; expect(e.childNodes.length).toBe(2); spanNode = e.childNodes[1]; expectTextNode(e.childNodes[0], 'Text'); expect(spanNode.tagName).toBe('SPAN'); expect(spanNode.childNodes.length).toBe(1); expectNode(spanNode.firstChild, TEXT_NODE_TYPE, 'More Text'); }); itRenders('a non-standard element with text', async render => { // This test suite generally assumes that we get exactly // the same warnings (or none) for all scenarios including // SSR + innerHTML, hydration, and client-side rendering. // However this particular warning fires only when creating // DOM nodes on the client side. We force it to fire early // so that it gets deduplicated later, and doesn't fail the test. expect(() => { ReactDOM.render(<nonstandard />, document.createElement('div')); }).toWarnDev('The tag <nonstandard> is unrecognized in this browser.'); const e = await render(<nonstandard>Text</nonstandard>); expect(e.tagName).toBe('NONSTANDARD'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a custom element with text', async render => { const e = await render(<custom-element>Text</custom-element>); expect(e.tagName).toBe('CUSTOM-ELEMENT'); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'Text'); }); itRenders('a leading blank child with a text sibling', async render => { const e = await render(<div>{''}foo</div>); if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], ''); expectTextNode(e.childNodes[1], 'foo'); } }); itRenders('a trailing blank child with a text sibling', async render => { const e = await render(<div>foo{''}</div>); // with Fiber, there are just two text nodes. if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], ''); } }); itRenders('an element with two text children', async render => { const e = await render( <div> {'foo'} {'bar'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[2], 'bar'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], 'bar'); } }); itRenders( 'a component returning text node between two text nodes', async render => { const B = () => 'b'; const e = await render( <div> {'a'} <B /> {'c'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expectTextNode(e.childNodes[4], 'c'); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expectTextNode(e.childNodes[2], 'c'); } }, ); itRenders('a tree with sibling host and text nodes', async render => { class X extends React.Component { render() { return [null, [<Y key="1" />], false]; } } function Y() { return [<Z key="1" />, ['c']]; } function Z() { return null; } const e = await render( <div> {[['a'], 'b']} <div> <X key="1" /> d </div> e </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's comments between text nodes. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expect(e.childNodes[3].childNodes.length).toBe(3); expectTextNode(e.childNodes[3].childNodes[0], 'c'); expectTextNode(e.childNodes[3].childNodes[2], 'd'); expectTextNode(e.childNodes[4], 'e'); } else { expect(e.childNodes.length).toBe(4); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expect(e.childNodes[2].childNodes.length).toBe(2); expectTextNode(e.childNodes[2].childNodes[0], 'c'); expectTextNode(e.childNodes[2].childNodes[1], 'd'); expectTextNode(e.childNodes[3], 'e'); } }); }); describe('number children', function() { itRenders('a number as single child', async render => { const e = await render(<div>{3}</div>); expect(e.textContent).toBe('3'); }); // zero is falsey, so it could look like no children if the code isn't careful. itRenders('zero as single child', async render => { const e = await render(<div>{0}</div>); expect(e.textContent).toBe('0'); }); itRenders('an element with number and text children', async render => { const e = await render( <div> {'foo'} {40} </div>, ); // with Fiber, there are just two text nodes. if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server markup there's a comment between. expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[2], '40'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], 'foo'); expectTextNode(e.childNodes[1], '40'); } }); }); describe('null, false, and undefined children', function() { itRenders('null single child as blank', async render => { const e = await render(<div>{null}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('false single child as blank', async render => { const e = await render(<div>{false}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('undefined single child as blank', async render => { const e = await render(<div>{undefined}</div>); expect(e.childNodes.length).toBe(0); }); itRenders('a null component children as empty', async render => { const NullComponent = () => null; const e = await render( <div> <NullComponent /> </div>, ); expect(e.childNodes.length).toBe(0); }); itRenders('null children as blank', async render => { const e = await render(<div>{null}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('false children as blank', async render => { const e = await render(<div>{false}foo</div>); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('null and false children together as blank', async render => { const e = await render( <div> {false} {null}foo{null} {false} </div>, ); expect(e.childNodes.length).toBe(1); expectTextNode(e.childNodes[0], 'foo'); }); itRenders('only null and false children as blank', async render => { const e = await render( <div> {false} {null} {null} {false} </div>, ); expect(e.childNodes.length).toBe(0); }); }); describe('elements with implicit namespaces', function() { itRenders('an svg element', async render => { const e = await render(<svg />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('svg'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); }); itRenders('svg child element with an attribute', async render => { let e = await render(<svg viewBox="0 0 0 0" />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('svg'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(e.getAttribute('viewBox')).toBe('0 0 0 0'); }); itRenders( 'svg child element with a namespace attribute', async render => { let e = await render( <svg> <image xlinkHref="http://i.imgur.com/w7GCRPb.png" /> </svg>, ); e = e.firstChild; expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('image'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); expect(e.getAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe( 'http://i.imgur.com/w7GCRPb.png', ); }, ); itRenders('svg child element with a badly cased alias', async render => { let e = await render( <svg> <image xlinkhref="http://i.imgur.com/w7GCRPb.png" /> </svg>, 1, ); e = e.firstChild; expect(e.hasAttributeNS('http://www.w3.org/1999/xlink', 'href')).toBe( false, ); expect(e.getAttribute('xlinkhref')).toBe( 'http://i.imgur.com/w7GCRPb.png', ); }); itRenders('svg element with a tabIndex attribute', async render => { let e = await render(<svg tabIndex="1" />); expect(e.tabIndex).toBe(1); }); itRenders( 'svg element with a badly cased tabIndex attribute', async render => { let e = await render(<svg tabindex="1" />, 1); expect(e.tabIndex).toBe(1); }, ); itRenders('svg element with a mixed case name', async render => { let e = await render( <svg> <filter> <feMorphology /> </filter> </svg>, ); e = e.firstChild.firstChild; expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('feMorphology'); expect(e.namespaceURI).toBe('http://www.w3.org/2000/svg'); }); itRenders('a math element', async render => { const e = await render(<math />); expect(e.childNodes.length).toBe(0); expect(e.tagName).toBe('math'); expect(e.namespaceURI).toBe('http://www.w3.org/1998/Math/MathML'); }); }); // specially wrapped components // (see the big switch near the beginning ofReactDOMComponent.mountComponent) itRenders('an img', async render => { const e = await render(<img />); expect(e.childNodes.length).toBe(0); expect(e.nextSibling).toBe(null); expect(e.tagName).toBe('IMG'); }); itRenders('a button', async render => { const e = await render(<button />); expect(e.childNodes.length).toBe(0); expect(e.nextSibling).toBe(null); expect(e.tagName).toBe('BUTTON'); }); itRenders('a div with dangerouslySetInnerHTML number', async render => { // Put dangerouslySetInnerHTML one level deeper because otherwise // hydrating from a bad markup would cause a mismatch (since we don't // patch dangerouslySetInnerHTML as text content). const e = (await render( <div> <span dangerouslySetInnerHTML={{__html: 0}} /> </div>, )).firstChild; expect(e.childNodes.length).toBe(1); expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE); expect(e.textContent).toBe('0'); }); itRenders('a div with dangerouslySetInnerHTML boolean', async render => { // Put dangerouslySetInnerHTML one level deeper because otherwise // hydrating from a bad markup would cause a mismatch (since we don't // patch dangerouslySetInnerHTML as text content). const e = (await render( <div> <span dangerouslySetInnerHTML={{__html: false}} /> </div>, )).firstChild; expect(e.childNodes.length).toBe(1); expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE); expect(e.firstChild.data).toBe('false'); }); itRenders( 'a div with dangerouslySetInnerHTML text string', async render => { // Put dangerouslySetInnerHTML one level deeper because otherwise // hydrating from a bad markup would cause a mismatch (since we don't // patch dangerouslySetInnerHTML as text content). const e = (await render( <div> <span dangerouslySetInnerHTML={{__html: 'hello'}} /> </div>, )).firstChild; expect(e.childNodes.length).toBe(1); expect(e.firstChild.nodeType).toBe(TEXT_NODE_TYPE); expect(e.textContent).toBe('hello'); }, ); itRenders( 'a div with dangerouslySetInnerHTML element string', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: "<span id='child'/>"}} />, ); expect(e.childNodes.length).toBe(1); expect(e.firstChild.tagName).toBe('SPAN'); expect(e.firstChild.getAttribute('id')).toBe('child'); expect(e.firstChild.childNodes.length).toBe(0); }, ); itRenders('a div with dangerouslySetInnerHTML object', async render => { const obj = { toString() { return "<span id='child'/>"; }, }; const e = await render(<div dangerouslySetInnerHTML={{__html: obj}} />); expect(e.childNodes.length).toBe(1); expect(e.firstChild.tagName).toBe('SPAN'); expect(e.firstChild.getAttribute('id')).toBe('child'); expect(e.firstChild.childNodes.length).toBe(0); }); itRenders( 'a div with dangerouslySetInnerHTML set to null', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: null}} />, ); expect(e.childNodes.length).toBe(0); }, ); itRenders( 'a div with dangerouslySetInnerHTML set to undefined', async render => { const e = await render( <div dangerouslySetInnerHTML={{__html: undefined}} />, ); expect(e.childNodes.length).toBe(0); }, ); itRenders('a noscript with children', async render => { const e = await render( <noscript> <div>Enable JavaScript to run this app.</div> </noscript>, ); if (render === clientCleanRender) { // On the client we ignore the contents of a noscript expect(e.childNodes.length).toBe(0); } else { // On the server or when hydrating the content should be correct expect(e.childNodes.length).toBe(1); expect(e.firstChild.textContent).toBe( '<div>Enable JavaScript to run this app.</div>', ); } }); describe('newline-eating elements', function() { itRenders( 'a newline-eating tag with content not starting with \\n', async render => { const e = await render(<pre>Hello</pre>); expect(e.textContent).toBe('Hello'); }, ); itRenders( 'a newline-eating tag with content starting with \\n', async render => { const e = await render(<pre>{'\nHello'}</pre>); expect(e.textContent).toBe('\nHello'); }, ); itRenders('a normal tag with content starting with \\n', async render => { const e = await render(<div>{'\nHello'}</div>); expect(e.textContent).toBe('\nHello'); }); }); describe('different component implementations', function() { function checkFooDiv(e) { expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, 'foo'); } itRenders('stateless components', async render => { const FunctionComponent = () => <div>foo</div>; checkFooDiv(await render(<FunctionComponent />)); }); itRenders('ES6 class components', async render => { class ClassComponent extends React.Component { render() { return <div>foo</div>; } } checkFooDiv(await render(<ClassComponent />)); }); itRenders('factory components', async render => { const FactoryComponent = () => { return { render: function() { return <div>foo</div>; }, }; }; checkFooDiv(await render(<FactoryComponent />)); }); }); describe('component hierarchies', async function() { itRenders('single child hierarchies of components', async render => { const Component = props => <div>{props.children}</div>; let e = await render( <Component> <Component> <Component> <Component /> </Component> </Component> </Component>, ); for (let i = 0; i < 3; i++) { expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(1); e = e.firstChild; } expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(0); }); itRenders('multi-child hierarchies of components', async render => { const Component = props => <div>{props.children}</div>; const e = await render( <Component> <Component> <Component /> <Component /> </Component> <Component> <Component /> <Component /> </Component> </Component>, ); expect(e.tagName).toBe('DIV'); expect(e.childNodes.length).toBe(2); for (let i = 0; i < 2; i++) { const child = e.childNodes[i]; expect(child.tagName).toBe('DIV'); expect(child.childNodes.length).toBe(2); for (let j = 0; j < 2; j++) { const grandchild = child.childNodes[j]; expect(grandchild.tagName).toBe('DIV'); expect(grandchild.childNodes.length).toBe(0); } } }); itRenders('a div with a child', async render => { const e = await render( <div id="parent"> <div id="child" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(1); expect(e.childNodes[0].id).toBe('child'); expect(e.childNodes[0].childNodes.length).toBe(0); }); itRenders('a div with multiple children', async render => { const e = await render( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, ); expect(e.id).toBe('parent'); expect(e.childNodes.length).toBe(2); expect(e.childNodes[0].id).toBe('child1'); expect(e.childNodes[0].childNodes.length).toBe(0); expect(e.childNodes[1].id).toBe('child2'); expect(e.childNodes[1].childNodes.length).toBe(0); }); itRenders( 'a div with multiple children separated by whitespace', async render => { const e = await render( <div id="parent"> <div id="child1" /> <div id="child2" /> </div>, ); expect(e.id).toBe('parent'); let child1, child2, textNode; expect(e.childNodes.length).toBe(3); child1 = e.childNodes[0]; textNode = e.childNodes[1]; child2 = e.childNodes[2]; expect(child1.id).toBe('child1'); expect(child1.childNodes.length).toBe(0); expectTextNode(textNode, ' '); expect(child2.id).toBe('child2'); expect(child2.childNodes.length).toBe(0); }, ); itRenders( 'a div with a single child surrounded by whitespace', async render => { // prettier-ignore const e = await render(<div id="parent"> <div id="child" /> </div>); // eslint-disable-line no-multi-spaces let textNode1, child, textNode2; expect(e.childNodes.length).toBe(3); textNode1 = e.childNodes[0]; child = e.childNodes[1]; textNode2 = e.childNodes[2]; expect(e.id).toBe('parent'); expectTextNode(textNode1, ' '); expect(child.id).toBe('child'); expect(child.childNodes.length).toBe(0); expectTextNode(textNode2, ' '); }, ); itRenders('a composite with multiple children', async render => { const Component = props => props.children; const e = await render( <Component>{['a', 'b', [undefined], [[false, 'c']]]}</Component>, ); let parent = e.parentNode; if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // For plain server markup result we have comments between. // If we're able to hydrate, they remain. expect(parent.childNodes.length).toBe(5); expectTextNode(parent.childNodes[0], 'a'); expectTextNode(parent.childNodes[2], 'b'); expectTextNode(parent.childNodes[4], 'c'); } else { expect(parent.childNodes.length).toBe(3); expectTextNode(parent.childNodes[0], 'a'); expectTextNode(parent.childNodes[1], 'b'); expectTextNode(parent.childNodes[2], 'c'); } }); }); describe('escaping >, <, and &', function() { itRenders('>,<, and & as single child', async render => { const e = await render(<div>{'<span>Text&quot;</span>'}</div>); expect(e.childNodes.length).toBe(1); expectNode(e.firstChild, TEXT_NODE_TYPE, '<span>Text&quot;</span>'); }); itRenders('>,<, and & as multiple children', async render => { const e = await render( <div> {'<span>Text1&quot;</span>'} {'<span>Text2&quot;</span>'} </div>, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); expectTextNode(e.childNodes[2], '<span>Text2&quot;</span>'); } else { expect(e.childNodes.length).toBe(2); expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); expectTextNode(e.childNodes[1], '<span>Text2&quot;</span>'); } }); }); describe('carriage return and null character', () => { // HTML parsing normalizes CR and CRLF to LF. // It also ignores null character. // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream // If we have a mismatch, it might be caused by that (and should not be reported). // We won't be patching up in this case as that matches our past behavior. itRenders( 'an element with one text child with special characters', async render => { const e = await render(<div>{'foo\rbar\r\nbaz\nqux\u0000'}</div>); if (render === serverRender || render === streamRender) { expect(e.childNodes.length).toBe(1); // Everything becomes LF when parsed from server HTML. // Null character is ignored. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar\nbaz\nqux'); } else { expect(e.childNodes.length).toBe(1); // Client rendering (or hydration) uses JS value with CR. // Null character stays. expectNode( e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar\r\nbaz\nqux\u0000', ); } }, ); itRenders( 'an element with two text children with special characters', async render => { const e = await render( <div> {'foo\rbar'} {'\r\nbaz\nqux\u0000'} </div>, ); if (render === serverRender || render === streamRender) { // We have three nodes because there is a comment between them. expect(e.childNodes.length).toBe(3); // Everything becomes LF when parsed from server HTML. // Null character is ignored. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\nbar'); expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\nbaz\nqux'); } else if (render === clientRenderOnServerString) { // We have three nodes because there is a comment between them. expect(e.childNodes.length).toBe(3); // Hydration uses JS value with CR and null character. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar'); expectNode(e.childNodes[2], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000'); } else { expect(e.childNodes.length).toBe(2); // Client rendering uses JS value with CR and null character. expectNode(e.childNodes[0], TEXT_NODE_TYPE, 'foo\rbar'); expectNode(e.childNodes[1], TEXT_NODE_TYPE, '\r\nbaz\nqux\u0000'); } }, ); itRenders( 'an element with an attribute value with special characters', async render => { const e = await render(<a title={'foo\rbar\r\nbaz\nqux\u0000'} />); if ( render === serverRender || render === streamRender || render === clientRenderOnServerString ) { // Everything becomes LF when parsed from server HTML. // Null character in an attribute becomes the replacement character. // Hydration also ends up with LF because we don't patch up attributes. expect(e.title).toBe('foo\nbar\nbaz\nqux\uFFFD'); } else { // Client rendering uses JS value with CR and null character. expect(e.title).toBe('foo\rbar\r\nbaz\nqux\u0000'); } }, ); }); describe('components that throw errors', function() { itThrowsWhenRendering( 'a function returning undefined', async render => { const UndefinedComponent = () => undefined; await render(<UndefinedComponent />, 1); }, 'UndefinedComponent(...): Nothing was returned from render. ' + 'This usually means a return statement is missing. Or, to ' + 'render nothing, return null.', ); itThrowsWhenRendering( 'a class returning undefined', async render => { class UndefinedComponent extends React.Component { render() { return undefined; } } await render(<UndefinedComponent />, 1); }, 'UndefinedComponent(...): Nothing was returned from render. ' + 'This usually means a return statement is missing. Or, to ' + 'render nothing, return null.', ); itThrowsWhenRendering( 'a function returning an object', async render => { const ObjectComponent = () => ({x: 123}); await render(<ObjectComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); itThrowsWhenRendering( 'a class returning an object', async render => { class ObjectComponent extends React.Component { render() { return {x: 123}; } } await render(<ObjectComponent />, 1); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); itThrowsWhenRendering( 'top-level object', async render => { await render({x: 123}); }, 'Objects are not valid as a React child (found: object with keys {x}).' + (__DEV__ ? ' If you meant to render a collection of children, use ' + 'an array instead.' : ''), ); }); describe('badly-typed elements', function() { itThrowsWhenRendering( 'object', async render => { let EmptyComponent = {}; expect(() => { EmptyComponent = <EmptyComponent />; }).toWarnDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: object. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.', {withoutStack: true}, ); await render(EmptyComponent); }, 'Element type is invalid: expected a string (for built-in components) or a class/function ' + '(for composite components) but got: object.' + (__DEV__ ? " You likely forgot to export your component from the file it's defined in, " + 'or you might have mixed up default and named imports.' : ''), ); itThrowsWhenRendering( 'null', async render => { let NullComponent = null; expect(() => { NullComponent = <NullComponent />; }).toWarnDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: null.', {withoutStack: true}, ); await render(NullComponent); }, 'Element type is invalid: expected a string (for built-in components) or a class/function ' + '(for composite components) but got: null', ); itThrowsWhenRendering( 'undefined', async render => { let UndefinedComponent = undefined; expect(() => { UndefinedComponent = <UndefinedComponent />; }).toWarnDev( 'Warning: React.createElement: type is invalid -- expected a string ' + '(for built-in components) or a class/function (for composite ' + 'components) but got: undefined. You likely forgot to export your ' + "component from the file it's defined in, or you might have mixed up " + 'default and named imports.', {withoutStack: true}, ); await render(UndefinedComponent); }, 'Element type is invalid: expected a string (for built-in components) or a class/function ' + '(for composite components) but got: undefined.' + (__DEV__ ? " You likely forgot to export your component from the file it's defined in, " + 'or you might have mixed up default and named imports.' : ''), ); }); }); });
(function () { var x = 10; if( x == 10){ console.log(`Welcome`); } })();
import { assert, InjectedProperty } from 'ember-metal'; /** Namespace for injection helper methods. @class inject @namespace Ember @static @public */ export default function inject() { assert(`Injected properties must be created through helpers, see '${Object.keys(inject).join('"', '"')}'`); } // Dictionary of injection validations by type, added to by `createInjectionHelper` const typeValidators = {}; /** This method allows other Ember modules to register injection helpers for a given container type. Helpers are exported to the `inject` namespace as the container type itself. @private @method createInjectionHelper @since 1.10.0 @for Ember @param {String} type The container type the helper will inject @param {Function} validator A validation callback that is executed at mixin-time */ export function createInjectionHelper(type, validator) { typeValidators[type] = validator; inject[type] = name => new InjectedProperty(type, name); } /** Validation function that runs per-type validation functions once for each injected type encountered. @private @method validatePropertyInjections @since 1.10.0 @for Ember @param {Object} factory The factory object */ export function validatePropertyInjections(factory) { let proto = factory.proto(); let types = []; for (let key in proto) { let desc = proto[key]; if (desc instanceof InjectedProperty && types.indexOf(desc.type) === -1) { types.push(desc.type); } } if (types.length) { for (let i = 0; i < types.length; i++) { let validator = typeValidators[types[i]]; if (typeof validator === 'function') { validator(factory); } } } return true; }
const path = require('path') const fs = require('fs-plus') const _ = require('underscore-plus') const {Emitter, Disposable, CompositeDisposable} = require('event-kit') const GitUtils = require('git-utils') let nextId = 0 // Extended: Represents the underlying git operations performed by Atom. // // This class shouldn't be instantiated directly but instead by accessing the // `atom.project` global and calling `getRepositories()`. Note that this will // only be available when the project is backed by a Git repository. // // This class handles submodules automatically by taking a `path` argument to many // of the methods. This `path` argument will determine which underlying // repository is used. // // For a repository with submodules this would have the following outcome: // // ```coffee // repo = atom.project.getRepositories()[0] // repo.getShortHead() # 'master' // repo.getShortHead('vendor/path/to/a/submodule') # 'dead1234' // ``` // // ## Examples // // ### Logging the URL of the origin remote // // ```coffee // git = atom.project.getRepositories()[0] // console.log git.getOriginURL() // ``` // // ### Requiring in packages // // ```coffee // {GitRepository} = require 'atom' // ``` module.exports = class GitRepository { static exists (path) { const git = this.open(path) if (git) { git.destroy() return true } else { return false } } /* Section: Construction and Destruction */ // Public: Creates a new GitRepository instance. // // * `path` The {String} path to the Git repository to open. // * `options` An optional {Object} with the following keys: // * `refreshOnWindowFocus` A {Boolean}, `true` to refresh the index and // statuses when the window is focused. // // Returns a {GitRepository} instance or `null` if the repository could not be opened. static open (path, options) { if (!path) { return null } try { return new GitRepository(path, options) } catch (error) { return null } } constructor (path, options = {}) { this.id = nextId++ this.emitter = new Emitter() this.subscriptions = new CompositeDisposable() this.repo = GitUtils.open(path) if (this.repo == null) { throw new Error(`No Git repository found searching path: ${path}`) } this.statusRefreshCount = 0 this.statuses = {} this.upstream = {ahead: 0, behind: 0} for (let submodulePath in this.repo.submodules) { const submoduleRepo = this.repo.submodules[submodulePath] submoduleRepo.upstream = {ahead: 0, behind: 0} } this.project = options.project this.config = options.config if (options.refreshOnWindowFocus || options.refreshOnWindowFocus == null) { const onWindowFocus = () => { this.refreshIndex() this.refreshStatus() } window.addEventListener('focus', onWindowFocus) this.subscriptions.add(new Disposable(() => window.removeEventListener('focus', onWindowFocus))) } if (this.project != null) { this.project.getBuffers().forEach(buffer => this.subscribeToBuffer(buffer)) this.subscriptions.add(this.project.onDidAddBuffer(buffer => this.subscribeToBuffer(buffer))) } } // Public: Destroy this {GitRepository} object. // // This destroys any tasks and subscriptions and releases the underlying // libgit2 repository handle. This method is idempotent. destroy () { this.repo = null if (this.emitter) { this.emitter.emit('did-destroy') this.emitter.dispose() this.emitter = null } if (this.subscriptions) { this.subscriptions.dispose() this.subscriptions = null } } // Public: Returns a {Boolean} indicating if this repository has been destroyed. isDestroyed () { return this.repo == null } // Public: Invoke the given callback when this GitRepository's destroy() method // is invoked. // // * `callback` {Function} // // Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy (callback) { return this.emitter.once('did-destroy', callback) } /* Section: Event Subscription */ // Public: Invoke the given callback when a specific file's status has // changed. When a file is updated, reloaded, etc, and the status changes, this // will be fired. // // * `callback` {Function} // * `event` {Object} // * `path` {String} the old parameters the decoration used to have // * `pathStatus` {Number} representing the status. This value can be passed to // {::isStatusModified} or {::isStatusNew} to get more information. // // Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangeStatus (callback) { return this.emitter.on('did-change-status', callback) } // Public: Invoke the given callback when a multiple files' statuses have // changed. For example, on window focus, the status of all the paths in the // repo is checked. If any of them have changed, this will be fired. Call // {::getPathStatus} to get the status for your path of choice. // // * `callback` {Function} // // Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChangeStatuses (callback) { return this.emitter.on('did-change-statuses', callback) } /* Section: Repository Details */ // Public: A {String} indicating the type of version control system used by // this repository. // // Returns `"git"`. getType () { return 'git' } // Public: Returns the {String} path of the repository. getPath () { if (this.path == null) { this.path = fs.absolute(this.getRepo().getPath()) } return this.path } // Public: Returns the {String} working directory path of the repository. getWorkingDirectory () { return this.getRepo().getWorkingDirectory() } // Public: Returns true if at the root, false if in a subfolder of the // repository. isProjectAtRoot () { if (this.projectAtRoot == null) { this.projectAtRoot = this.project && this.project.relativize(this.getWorkingDirectory()) === '' } return this.projectAtRoot } // Public: Makes a path relative to the repository's working directory. relativize (path) { return this.getRepo().relativize(path) } // Public: Returns true if the given branch exists. hasBranch (branch) { return this.getReferenceTarget(`refs/heads/${branch}`) != null } // Public: Retrieves a shortened version of the HEAD reference value. // // This removes the leading segments of `refs/heads`, `refs/tags`, or // `refs/remotes`. It also shortens the SHA-1 of a detached `HEAD` to 7 // characters. // // * `path` An optional {String} path in the repository to get this information // for, only needed if the repository contains submodules. // // Returns a {String}. getShortHead (path) { return this.getRepo(path).getShortHead() } // Public: Is the given path a submodule in the repository? // // * `path` The {String} path to check. // // Returns a {Boolean}. isSubmodule (filePath) { if (!filePath) return false const repo = this.getRepo(filePath) if (repo.isSubmodule(repo.relativize(filePath))) { return true } else { // Check if the filePath is a working directory in a repo that isn't the root. return repo !== this.getRepo() && repo.relativize(path.join(filePath, 'dir')) === 'dir' } } // Public: Returns the number of commits behind the current branch is from the // its upstream remote branch. // // * `reference` The {String} branch reference name. // * `path` The {String} path in the repository to get this information for, // only needed if the repository contains submodules. getAheadBehindCount (reference, path) { return this.getRepo(path).getAheadBehindCount(reference) } // Public: Get the cached ahead/behind commit counts for the current branch's // upstream branch. // // * `path` An optional {String} path in the repository to get this information // for, only needed if the repository has submodules. // // Returns an {Object} with the following keys: // * `ahead` The {Number} of commits ahead. // * `behind` The {Number} of commits behind. getCachedUpstreamAheadBehindCount (path) { return this.getRepo(path).upstream || this.upstream } // Public: Returns the git configuration value specified by the key. // // * `key` The {String} key for the configuration to lookup. // * `path` An optional {String} path in the repository to get this information // for, only needed if the repository has submodules. getConfigValue (key, path) { return this.getRepo(path).getConfigValue(key) } // Public: Returns the origin url of the repository. // // * `path` (optional) {String} path in the repository to get this information // for, only needed if the repository has submodules. getOriginURL (path) { return this.getConfigValue('remote.origin.url', path) } // Public: Returns the upstream branch for the current HEAD, or null if there // is no upstream branch for the current HEAD. // // * `path` An optional {String} path in the repo to get this information for, // only needed if the repository contains submodules. // // Returns a {String} branch name such as `refs/remotes/origin/master`. getUpstreamBranch (path) { return this.getRepo(path).getUpstreamBranch() } // Public: Gets all the local and remote references. // // * `path` An optional {String} path in the repository to get this information // for, only needed if the repository has submodules. // // Returns an {Object} with the following keys: // * `heads` An {Array} of head reference names. // * `remotes` An {Array} of remote reference names. // * `tags` An {Array} of tag reference names. getReferences (path) { return this.getRepo(path).getReferences() } // Public: Returns the current {String} SHA for the given reference. // // * `reference` The {String} reference to get the target of. // * `path` An optional {String} path in the repo to get the reference target // for. Only needed if the repository contains submodules. getReferenceTarget (reference, path) { return this.getRepo(path).getReferenceTarget(reference) } /* Section: Reading Status */ // Public: Returns true if the given path is modified. // // * `path` The {String} path to check. // // Returns a {Boolean} that's true if the `path` is modified. isPathModified (path) { return this.isStatusModified(this.getPathStatus(path)) } // Public: Returns true if the given path is new. // // * `path` The {String} path to check. // // Returns a {Boolean} that's true if the `path` is new. isPathNew (path) { return this.isStatusNew(this.getPathStatus(path)) } // Public: Is the given path ignored? // // * `path` The {String} path to check. // // Returns a {Boolean} that's true if the `path` is ignored. isPathIgnored (path) { return this.getRepo().isIgnored(this.relativize(path)) } // Public: Get the status of a directory in the repository's working directory. // // * `path` The {String} path to check. // // Returns a {Number} representing the status. This value can be passed to // {::isStatusModified} or {::isStatusNew} to get more information. getDirectoryStatus (directoryPath) { directoryPath = `${this.relativize(directoryPath)}/` let directoryStatus = 0 for (let statusPath in this.statuses) { const status = this.statuses[statusPath] if (statusPath.startsWith(directoryPath)) directoryStatus |= status } return directoryStatus } // Public: Get the status of a single path in the repository. // // * `path` A {String} repository-relative path. // // Returns a {Number} representing the status. This value can be passed to // {::isStatusModified} or {::isStatusNew} to get more information. getPathStatus (path) { const repo = this.getRepo(path) const relativePath = this.relativize(path) const currentPathStatus = this.statuses[relativePath] || 0 let pathStatus = repo.getStatus(repo.relativize(path)) || 0 if (repo.isStatusIgnored(pathStatus)) pathStatus = 0 if (pathStatus > 0) { this.statuses[relativePath] = pathStatus } else { delete this.statuses[relativePath] } if (currentPathStatus !== pathStatus) { this.emitter.emit('did-change-status', {path, pathStatus}) } return pathStatus } // Public: Get the cached status for the given path. // // * `path` A {String} path in the repository, relative or absolute. // // Returns a status {Number} or null if the path is not in the cache. getCachedPathStatus (path) { return this.statuses[this.relativize(path)] } // Public: Returns true if the given status indicates modification. // // * `status` A {Number} representing the status. // // Returns a {Boolean} that's true if the `status` indicates modification. isStatusModified (status) { return this.getRepo().isStatusModified(status) } // Public: Returns true if the given status indicates a new path. // // * `status` A {Number} representing the status. // // Returns a {Boolean} that's true if the `status` indicates a new path. isStatusNew (status) { return this.getRepo().isStatusNew(status) } /* Section: Retrieving Diffs */ // Public: Retrieves the number of lines added and removed to a path. // // This compares the working directory contents of the path to the `HEAD` // version. // // * `path` The {String} path to check. // // Returns an {Object} with the following keys: // * `added` The {Number} of added lines. // * `deleted` The {Number} of deleted lines. getDiffStats (path) { const repo = this.getRepo(path) return repo.getDiffStats(repo.relativize(path)) } // Public: Retrieves the line diffs comparing the `HEAD` version of the given // path and the given text. // // * `path` The {String} path relative to the repository. // * `text` The {String} to compare against the `HEAD` contents // // Returns an {Array} of hunk {Object}s with the following keys: // * `oldStart` The line {Number} of the old hunk. // * `newStart` The line {Number} of the new hunk. // * `oldLines` The {Number} of lines in the old hunk. // * `newLines` The {Number} of lines in the new hunk getLineDiffs (path, text) { // Ignore eol of line differences on windows so that files checked in as // LF don't report every line modified when the text contains CRLF endings. const options = {ignoreEolWhitespace: process.platform === 'win32'} const repo = this.getRepo(path) return repo.getLineDiffs(repo.relativize(path), text, options) } /* Section: Checking Out */ // Public: Restore the contents of a path in the working directory and index // to the version at `HEAD`. // // This is essentially the same as running: // // ```sh // git reset HEAD -- <path> // git checkout HEAD -- <path> // ``` // // * `path` The {String} path to checkout. // // Returns a {Boolean} that's true if the method was successful. checkoutHead (path) { const repo = this.getRepo(path) const headCheckedOut = repo.checkoutHead(repo.relativize(path)) if (headCheckedOut) this.getPathStatus(path) return headCheckedOut } // Public: Checks out a branch in your repository. // // * `reference` The {String} reference to checkout. // * `create` A {Boolean} value which, if true creates the new reference if // it doesn't exist. // // Returns a Boolean that's true if the method was successful. checkoutReference (reference, create) { return this.getRepo().checkoutReference(reference, create) } /* Section: Private */ // Subscribes to buffer events. subscribeToBuffer (buffer) { const getBufferPathStatus = () => { const bufferPath = buffer.getPath() if (bufferPath) this.getPathStatus(bufferPath) } getBufferPathStatus() const bufferSubscriptions = new CompositeDisposable() bufferSubscriptions.add(buffer.onDidSave(getBufferPathStatus)) bufferSubscriptions.add(buffer.onDidReload(getBufferPathStatus)) bufferSubscriptions.add(buffer.onDidChangePath(getBufferPathStatus)) bufferSubscriptions.add(buffer.onDidDestroy(() => { bufferSubscriptions.dispose() return this.subscriptions.remove(bufferSubscriptions) })) this.subscriptions.add(bufferSubscriptions) } // Subscribes to editor view event. checkoutHeadForEditor (editor) { const buffer = editor.getBuffer() const bufferPath = buffer.getPath() if (bufferPath) { this.checkoutHead(bufferPath) return buffer.reload() } } // Returns the corresponding {Repository} getRepo (path) { if (this.repo) { return this.repo.submoduleForPath(path) || this.repo } else { throw new Error('Repository has been destroyed') } } // Reread the index to update any values that have changed since the // last time the index was read. refreshIndex () { return this.getRepo().refreshIndex() } // Refreshes the current git status in an outside process and asynchronously // updates the relevant properties. async refreshStatus () { const statusRefreshCount = ++this.statusRefreshCount const repo = this.getRepo() const relativeProjectPaths = this.project && this.project.getPaths() .map(projectPath => this.relativize(projectPath)) .filter(projectPath => (projectPath.length > 0) && !path.isAbsolute(projectPath)) const branch = await repo.getHeadAsync() const upstream = await repo.getAheadBehindCountAsync() const statuses = {} const repoStatus = relativeProjectPaths.length > 0 ? await repo.getStatusAsync(relativeProjectPaths) : await repo.getStatusAsync() for (let filePath in repoStatus) { statuses[filePath] = repoStatus[filePath] } const submodules = {} for (let submodulePath in repo.submodules) { const submoduleRepo = repo.submodules[submodulePath] submodules[submodulePath] = { branch: await submoduleRepo.getHeadAsync(), upstream: await submoduleRepo.getAheadBehindCountAsync() } const workingDirectoryPath = submoduleRepo.getWorkingDirectory() const submoduleStatus = await submoduleRepo.getStatusAsync() for (let filePath in submoduleStatus) { const absolutePath = path.join(workingDirectoryPath, filePath) const relativizePath = repo.relativize(absolutePath) statuses[relativizePath] = submoduleStatus[filePath] } } if (this.statusRefreshCount !== statusRefreshCount || this.isDestroyed()) return const statusesUnchanged = _.isEqual(branch, this.branch) && _.isEqual(statuses, this.statuses) && _.isEqual(upstream, this.upstream) && _.isEqual(submodules, this.submodules) this.branch = branch this.statuses = statuses this.upstream = upstream this.submodules = submodules for (let submodulePath in repo.submodules) { repo.submodules[submodulePath].upstream = submodules[submodulePath].upstream } if (!statusesUnchanged) this.emitter.emit('did-change-statuses') } }
.1n;
define(['angular', 'modules/invoices/indexController', 'modules/invoices/newController', 'modules/invoices/editController'], function(angular, IndexController, NewController, EditController) { 'use strict'; var configFn = []; var invoices = angular.module('invoices', configFn); invoices.controller('invoices.controllers.index', IndexController); invoices.controller('invoices.controllers.new', NewController); invoices.controller('invoices.controllers.edit', EditController); invoices.config(['$stateProvider', function($stateProvider) { $stateProvider. state('app.invoices', { url: 'invoices', views: { 'top-menu@app': { templateUrl: 'src/modules/invoices/top-menu.tpl.html', controller: 'base.controllers.navigation' }, 'center@app': { templateUrl: 'src/modules/invoices/index.tpl.html', controller: 'invoices.controllers.index' } }, needsAuthority: 'ROLE_ADMIN' }); }]); return invoices; });
suite('PacketLinkFactory', function() { setup(function() { wdi.Debug.debug = false; //disable debugging, it slows tests }); suite('#extract()', function() { test('Should extract generation from a RedSetAck', function() { var arr = [0x01, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00]; var myHeader = new wdi.SpiceDataHeader({type:wdi.SpiceVars.SPICE_MSG_SET_ACK, size: 8}); var queue = new wdi.ViewQueue(); queue.push(arr); var spiceSetAck = wdi.PacketLinkFactory.extract(myHeader, queue); assert.strictEqual(spiceSetAck.generation, 1); }); test('Should extract id from a RedPing', function() { var arr = [0x01, 0x00, 0x00, 0x00, 0xea, 0x00, 0x72, 0xc3, 0x00, 0x00, 0x00, 0x00]; var myHeader = new wdi.SpiceDataHeader({type:wdi.SpiceVars.SPICE_MSG_PING, size: 12}); var queue = new wdi.ViewQueue(); queue.push(arr); var spicePing = wdi.PacketLinkFactory.extract(myHeader, queue); assert.strictEqual(spicePing.id, 1); }); test('Should extract time from a RedPing and it will be an instance of BigInteger', function() { var arr = [0x01, 0x00, 0x00, 0x00, 0xea, 0x00, 0x72, 0xc3, 0x00, 0x00, 0x00, 0x00]; var myHeader = new wdi.SpiceDataHeader({type:wdi.SpiceVars.SPICE_MSG_PING, size: 12}); var queue = new wdi.ViewQueue(); queue.push(arr); var spicePing = wdi.PacketLinkFactory.extract(myHeader, queue); assert.instanceOf(spicePing.time, BigInteger); }); test('Should extract a Migrate message', function() { var arr = [0x0a, 0x00, 0x00, 0x00]; var myHeader = new wdi.SpiceDataHeader({type:wdi.SpiceVars.SPICE_MSG_MIGRATE, size: 4}); var queue = new wdi.ViewQueue(); queue.push(arr); var spiceMigrate = wdi.PacketLinkFactory.extract(myHeader, queue); assert.strictEqual(spiceMigrate.flags, 10); }); test('Should extract a Migrate Data message that is a vector', function() { var arr = [0x0a, 0x03, 0x02, 0x05]; var myHeader = new wdi.SpiceDataHeader({type:wdi.SpiceVars.SPICE_MSG_MIGRATE_DATA, size: 4}); var queue = new wdi.Queue(); queue.push(arr); var spiceMigrateData = wdi.PacketLinkFactory.extract(myHeader, queue); assert.deepEqual(spiceMigrateData.vector, [10, 3, 2, 5]); }); }); }); suite('PacketLinkProcess', function() { setup(function() { wdi.Debug.debug = false; //disable debugging, it slows tests }); suite('#process()', function() { test('Should process spice main init', function() { }); }); });
Ember.TEMPLATES["test/fixtures/grandparent/parent/child"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {}; data.buffer.push("Should be nested."); }); Ember.TEMPLATES["test/fixtures/simple"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {}; var buffer = '', hashTypes, hashContexts, escapeExpression=this.escapeExpression; data.buffer.push("<p>Hello, my name is "); hashTypes = {}; hashContexts = {}; data.buffer.push(escapeExpression(helpers._triageMustache.call(depth0, "name", {hash:{},contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data}))); data.buffer.push(".</p>"); return buffer; }); Ember.TEMPLATES["test/fixtures/text"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {}; data.buffer.push("Basic template that does nothing."); });
/** * Plugin.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class contains all core logic for the nonbreaking plugin. * * @class tinymce.nonbreaking.Plugin * @private */ define( 'tinymce.plugins.nonbreaking.Plugin', [ 'tinymce.core.PluginManager', 'tinymce.plugins.nonbreaking.api.Commands', 'tinymce.plugins.nonbreaking.core.Keyboard', 'tinymce.plugins.nonbreaking.ui.Buttons' ], function (PluginManager, Commands, Keyboard, Buttons) { PluginManager.add('nonbreaking', function (editor) { Commands.register(editor); Buttons.register(editor); Keyboard.setup(editor); }); return function () { }; } );
'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute', 'myApp.view1', 'myApp.view2', 'myApp.version' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]);
function ResourceManager(options) { var t = this; // exports t.fetchResources = fetchResources; t.setResources = setResources; t.mutateResourceEvent = mutateResourceEvent; // locals var resourceSources = []; var cache; // initialize the resources. setResources(options.resources); // add the resource sources function setResources(sources) { resourceSources = []; var resource; if ($.isFunction(sources)) { // is it a function? resource = { resources: sources }; resourceSources.push(resource); cache = undefined; } else if (typeof sources == 'string') { // is it a URL string? resource = { url: sources }; resourceSources.push(resource); cache = undefined; } else if (typeof sources == 'object' && sources != null) { // is it json object? for (var i = 0; i < sources.length; i++) { var s = sources[i]; normalizeSource(s); resource = { resources: s }; resourceSources.push(resource); } cache = undefined; } } /** * ---------------------------------------------------------------- * Fetch resources from source array * ---------------------------------------------------------------- */ function fetchResources(useCache, currentView) { var resources; // if useCache is not defined, default to true if (useCache || useCache === undefined || cache === undefined) { // do a fetch resource from source, rebuild cache cache = []; var len = resourceSources.length; for (var i = 0; i < len; i++) { cache = cache.concat(fetchResourceSource(resourceSources[i], currentView)); } } if($.isFunction(options.resourceFilter)) { resources = $.grep(cache, options.resourceFilter); } else { resources = cache; } if($.isFunction(options.resourceSort)) { //todo! does it need to copy array first? resources.sort(options.resourceSort); } return resources; } /** * ---------------------------------------------------------------- * Fetch resources from each source. If source is a function, call * the function and return the resource. If source is a URL, get * the data via synchronized ajax call. If the source is an * object, return it as is. * ---------------------------------------------------------------- */ function fetchResourceSource(source, currentView) { var resources = source.resources; if (resources) { if ($.isFunction(resources)) { return resources(); } } else { var url = source.url; if (url) { var data = {}; if (typeof currentView === 'object') { var startParam = options.startParam; var endParam = options.endParam; if (startParam) { data[startParam] = Math.round(+currentView.intervalStart / 1000); } if (endParam) { data[endParam] = Math.round(+currentView.intervalEnd / 1000); } } $.ajax($.extend({}, ajaxDefaults, source, { data: data, dataType: 'json', cache: false, success: function(res) { res = res || []; resources = res; }, error: function() { // TODO - need to rewrite callbacks, etc. //alert("ajax error getting json from " + url); }, async: false // too much work coordinating callbacks so dumb it down })); } } return resources; } /** * ---------------------------------------------------------------- * normalize the source object * ---------------------------------------------------------------- */ function normalizeSource(source) { if (source.className) { if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } } else { source.className = []; } var normalizers = fc.sourceNormalizers; for (var i = 0; i < normalizers.length; i++) { normalizers[i](source); } } /* Event Modification Math -----------------------------------------------------------------------------------------*/ // Modify the date(s) of an event and make this change propagate to all other events with // the same ID (related repeating events). // // If `newStart`/`newEnd` are not specified, the "new" dates are assumed to be `event.start` and `event.end`. // The "old" dates to be compare against are always `event._start` and `event._end` (set by EventManager). // // Returns an object with delta information and a function to undo all operations. // function mutateResourceEvent(event, newResources, newStart, newEnd) { var oldAllDay = event._allDay; var oldStart = event._start; var oldEnd = event._end; var clearEnd = false; var newAllDay; var dateDelta; var durationDelta; var undoFunc; // if no new dates were passed in, compare against the event's existing dates if (!newStart && !newEnd) { newStart = event.start; newEnd = event.end; } // NOTE: throughout this function, the initial values of `newStart` and `newEnd` are // preserved. These values may be undefined. // detect new allDay if (event.allDay != oldAllDay) { // if value has changed, use it newAllDay = event.allDay; } else { // otherwise, see if any of the new dates are allDay newAllDay = !(newStart || newEnd).hasTime(); } // normalize the new dates based on allDay if (newAllDay) { if (newStart) { newStart = newStart.clone().stripTime(); } if (newEnd) { newEnd = newEnd.clone().stripTime(); } } // compute dateDelta if (newStart) { if (newAllDay) { dateDelta = dayishDiff(newStart, oldStart.clone().stripTime()); // treat oldStart as allDay } else { dateDelta = dayishDiff(newStart, oldStart); } } if (newAllDay != oldAllDay) { // if allDay has changed, always throw away the end clearEnd = true; } else if (newEnd) { durationDelta = dayishDiff( // new duration newEnd || t.getDefaultEventEnd(newAllDay, newStart || oldStart), newStart || oldStart ).subtract(dayishDiff( // subtract old duration oldEnd || t.getDefaultEventEnd(oldAllDay, oldStart), oldStart )); } undoFunc = mutateResourceEvents( t.clientEvents(event._id), // get events with this ID clearEnd, newAllDay, dateDelta, durationDelta, newResources ); return { dateDelta: dateDelta, durationDelta: durationDelta, undo: undoFunc }; } // Modifies an array of events in the following ways (operations are in order): // - clear the event's `end` // - convert the event to allDay // - add `dateDelta` to the start and end // - add `durationDelta` to the event's duration // // Returns a function that can be called to undo all the operations. // function mutateResourceEvents(events, clearEnd, forceAllDay, dateDelta, durationDelta, newResources) { var isAmbigTimezone = t.getIsAmbigTimezone(); var undoFunctions = []; $.each(events, function(i, event) { var oldResources = event.resources; var oldAllDay = event._allDay; var oldStart = event._start; var oldEnd = event._end; var newAllDay = forceAllDay != null ? forceAllDay : oldAllDay; var newStart = oldStart.clone(); var newEnd = (!clearEnd && oldEnd) ? oldEnd.clone() : null; // NOTE: this function is responsible for transforming `newStart` and `newEnd`, // which were initialized to the OLD values first. `newEnd` may be null. // normlize newStart/newEnd to be consistent with newAllDay if (newAllDay) { newStart.stripTime(); if (newEnd) { newEnd.stripTime(); } } else { if (!newStart.hasTime()) { newStart = t.rezoneDate(newStart); } if (newEnd && !newEnd.hasTime()) { newEnd = t.rezoneDate(newEnd); } } // ensure we have an end date if necessary if (!newEnd && (options.forceEventDuration || +durationDelta)) { newEnd = t.getDefaultEventEnd(newAllDay, newStart); } // translate the dates newStart.add(dateDelta); if (newEnd) { newEnd.add(dateDelta).add(durationDelta); } // if the dates have changed, and we know it is impossible to recompute the // timezone offsets, strip the zone. if (isAmbigTimezone) { if (+dateDelta || +durationDelta) { newStart.stripZone(); if (newEnd) { newEnd.stripZone(); } } } event.allDay = newAllDay; event.start = newStart; event.end = newEnd; event.resources = newResources; backupEventDates(event); undoFunctions.push(function() { event.allDay = oldAllDay; event.start = oldStart; event.end = oldEnd; event.resources = oldResources; backupEventDates(event); }); }); return function() { for (var i=0; i<undoFunctions.length; i++) { undoFunctions[i](); } }; } }
import Base from './base'; // decode websafe_json encoding function unsafeJson(text) { return text.replace(/&gt;/g, '>') .replace(/&lt;/g, '<') .replace(/&amp;/g, '&'); } class Stylesheet extends Base { _type = 'Stylesheet'; get stylesheet () { return unsafeJson(this.get('stylesheet')); } } export default Stylesheet;
/* * jQuery File Upload Plugin 3.8 * * Copyright 2010, Sebastian Tschan, AQUANTUM * Licensed under the MIT license: * http://creativecommons.org/licenses/MIT/ * * https://blueimp.net * http://www.aquantum.de * GitHub: https://github.com/blueimp/jQuery-File-Upload/wiki */ /*jslint browser: true */ /*global File, FileReader, FormData, unescape, jQuery */ (function ($) { var defaultNamespace = 'file_upload', undef = 'undefined', func = 'function', num = 'number', FileUpload, methods, MultiLoader = function (callBack, numberComplete) { var loaded = 0; this.complete = function () { loaded += 1; if (loaded === numberComplete) { callBack(); } }; }; FileUpload = function (container) { var fileUpload = this, uploadForm, fileInput, settings = { namespace: defaultNamespace, uploadFormFilter: function (index) { return true; }, fileInputFilter: function (index) { return true; }, cssClass: defaultNamespace, dragDropSupport: true, dropZone: container, url: function (form) { return form.attr('action'); }, method: function (form) { return form.attr('method'); }, fieldName: function (input) { return input.attr('name'); }, formData: function (form) { return form.serializeArray(); }, multipart: true, multiFileRequest: false, withCredentials: false, forceIframeUpload: false }, documentListeners = {}, dropZoneListeners = {}, protocolRegExp = /^http(s)?:\/\//, optionsReference, isXHRUploadCapable = function () { return typeof XMLHttpRequest !== undef && typeof File !== undef && ( !settings.multipart || typeof FormData !== undef || typeof FileReader !== undef ); }, initEventHandlers = function () { if (settings.dragDropSupport) { if (typeof settings.onDocumentDragEnter === func) { documentListeners['dragenter.' + settings.namespace] = function (e) { settings.onDocumentDragEnter(e); }; } if (typeof settings.onDocumentDragLeave === func) { documentListeners['dragleave.' + settings.namespace] = function (e) { settings.onDocumentDragLeave(e); }; } documentListeners['dragover.' + settings.namespace] = fileUpload.onDocumentDragOver; documentListeners['drop.' + settings.namespace] = fileUpload.onDocumentDrop; $(document).bind(documentListeners); if (typeof settings.onDragEnter === func) { dropZoneListeners['dragenter.' + settings.namespace] = function (e) { settings.onDragEnter(e); }; } if (typeof settings.onDragLeave === func) { dropZoneListeners['dragleave.' + settings.namespace] = function (e) { settings.onDragLeave(e); }; } dropZoneListeners['dragover.' + settings.namespace] = fileUpload.onDragOver; dropZoneListeners['drop.' + settings.namespace] = fileUpload.onDrop; settings.dropZone.bind(dropZoneListeners); } fileInput.bind('change.' + settings.namespace, fileUpload.onChange); }, removeEventHandlers = function () { $.each(documentListeners, function (key, value) { $(document).unbind(key, value); }); $.each(dropZoneListeners, function (key, value) { settings.dropZone.unbind(key, value); }); fileInput.unbind('change.' + settings.namespace); }, initUploadEventHandlers = function (files, index, xhr, settings) { if (typeof settings.onProgress === func) { xhr.upload.onprogress = function (e) { settings.onProgress(e, files, index, xhr, settings); }; } if (typeof settings.onLoad === func) { xhr.onload = function (e) { settings.onLoad(e, files, index, xhr, settings); }; } if (typeof settings.onAbort === func) { xhr.onabort = function (e) { settings.onAbort(e, files, index, xhr, settings); }; } if (typeof settings.onError === func) { xhr.onerror = function (e) { settings.onError(e, files, index, xhr, settings); }; } }, getUrl = function (settings) { if (typeof settings.url === func) { return settings.url(settings.uploadForm || uploadForm); } return settings.url; }, getMethod = function (settings) { if (typeof settings.method === func) { return settings.method(settings.uploadForm || uploadForm); } return settings.method; }, getFieldName = function (settings) { if (typeof settings.fieldName === func) { return settings.fieldName(settings.fileInput || fileInput); } return settings.fieldName; }, getFormData = function (settings) { var formData; if (typeof settings.formData === func) { return settings.formData(settings.uploadForm || uploadForm); } else if ($.isArray(settings.formData)) { return settings.formData; } else if (settings.formData) { formData = []; $.each(settings.formData, function (name, value) { formData.push({name: name, value: value}); }); return formData; } return []; }, isSameDomain = function (url) { if (protocolRegExp.test(url)) { var host = location.host, indexStart = location.protocol.length + 2, index = url.indexOf(host, indexStart), pathIndex = index + host.length; if ((index === indexStart || index === url.indexOf('@', indexStart) + 1) && (url.length === pathIndex || $.inArray(url.charAt(pathIndex), ['/', '?', '#']) !== -1)) { return true; } return false; } return true; }, setRequestHeaders = function (xhr, settings, sameDomain) { if (sameDomain) { xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); } else if (settings.withCredentials) { xhr.withCredentials = true; } if ($.isArray(settings.requestHeaders)) { $.each(settings.requestHeaders, function (index, header) { xhr.setRequestHeader(header[0], header[1]); }); } else if (settings.requestHeaders) { $.each(settings.requestHeaders, function (name, value) { xhr.setRequestHeader(name, value); }); } }, nonMultipartUpload = function (file, xhr, sameDomain) { if (sameDomain) { xhr.setRequestHeader('X-File-Name', unescape(encodeURIComponent(file.name))); } xhr.setRequestHeader('Content-Type', file.type); xhr.send(file); }, formDataUpload = function (files, xhr, settings) { var formData = new FormData(), i; $.each(getFormData(settings), function (index, field) { formData.append(field.name, field.value); }); for (i = 0; i < files.length; i += 1) { formData.append(getFieldName(settings), files[i]); } xhr.send(formData); }, loadFileContent = function (file, callBack) { var fileReader = new FileReader(); fileReader.onload = function (e) { file.content = e.target.result; callBack(); }; fileReader.readAsBinaryString(file); }, buildMultiPartFormData = function (boundary, files, filesFieldName, fields) { var doubleDash = '--', crlf = '\r\n', formData = ''; $.each(fields, function (index, field) { formData += doubleDash + boundary + crlf + 'Content-Disposition: form-data; name="' + unescape(encodeURIComponent(field.name)) + '"' + crlf + crlf + unescape(encodeURIComponent(field.value)) + crlf; }); $.each(files, function (index, file) { formData += doubleDash + boundary + crlf + 'Content-Disposition: form-data; name="' + unescape(encodeURIComponent(filesFieldName)) + '"; filename="' + unescape(encodeURIComponent(file.name)) + '"' + crlf + 'Content-Type: ' + file.type + crlf + crlf + file.content + crlf; }); formData += doubleDash + boundary + doubleDash + crlf; return formData; }, fileReaderUpload = function (files, xhr, settings) { var boundary = '----MultiPartFormBoundary' + (new Date()).getTime(), loader, i; xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); loader = new MultiLoader(function () { xhr.sendAsBinary(buildMultiPartFormData( boundary, files, getFieldName(settings), getFormData(settings) )); }, files.length); for (i = 0; i < files.length; i += 1) { loadFileContent(files[i], loader.complete); } }, upload = function (files, index, xhr, settings) { var url = getUrl(settings), sameDomain = isSameDomain(url), filesToUpload; initUploadEventHandlers(files, index, xhr, settings); xhr.open(getMethod(settings), url, true); setRequestHeaders(xhr, settings, sameDomain); if (!settings.multipart) { nonMultipartUpload(files[index], xhr, sameDomain); } else { if (typeof index === num) { filesToUpload = [files[index]]; } else { filesToUpload = files; } if (typeof FormData !== undef) { formDataUpload(filesToUpload, xhr, settings); } else if (typeof FileReader !== undef) { fileReaderUpload(filesToUpload, xhr, settings); } else { $.error('Browser does neither support FormData nor FileReader interface'); } } }, handleUpload = function (event, files, input, form, index) { var xhr = new XMLHttpRequest(), uploadSettings = $.extend({}, settings); uploadSettings.fileInput = input; uploadSettings.uploadForm = form; if (typeof uploadSettings.initUpload === func) { uploadSettings.initUpload( event, files, index, xhr, uploadSettings, function () { upload(files, index, xhr, uploadSettings); } ); } else { upload(files, index, xhr, uploadSettings); } }, handleFiles = function (event, files, input, form) { var i; if (settings.multiFileRequest) { handleUpload(event, files, input, form); } else { for (i = 0; i < files.length; i += 1) { handleUpload(event, files, input, form, i); } } }, legacyUploadFormDataInit = function (input, form, settings) { var formData = getFormData(settings); form.find(':input').not(':disabled') .attr('disabled', true) .addClass(settings.namespace + '_disabled'); $.each(formData, function (index, field) { $('<input type="hidden"/>') .attr('name', field.name) .val(field.value) .addClass(settings.namespace + '_form_data') .appendTo(form); }); input .attr('name', getFieldName(settings)) .appendTo(form); }, legacyUploadFormDataReset = function (input, form, settings) { input.detach(); form.find('.' + settings.namespace + '_disabled') .removeAttr('disabled') .removeClass(settings.namespace + '_disabled'); form.find('.' + settings.namespace + '_form_data').remove(); }, legacyUpload = function (input, form, iframe, settings) { var originalAction = form.attr('action'), originalMethod = form.attr('method'), originalTarget = form.attr('target'); iframe .unbind('abort') .bind('abort', function (e) { iframe.readyState = 0; // javascript:false as iframe src prevents warning popups on HTTPS in IE6 // concat is used here to prevent the "Script URL" JSLint error: iframe.unbind('load').attr('src', 'javascript'.concat(':false;')); if (typeof settings.onAbort === func) { settings.onAbort(e, [{name: input.val(), type: null, size: null}], 0, iframe, settings); } }) .unbind('load') .bind('load', function (e) { iframe.readyState = 4; if (typeof settings.onLoad === func) { settings.onLoad(e, [{name: input.val(), type: null, size: null}], 0, iframe, settings); } // Fix for IE endless progress bar activity bug (happens on form submits to iframe targets): $('<iframe src="javascript:false;" style="display:none"></iframe>').appendTo(form).remove(); }); form .attr('action', getUrl(settings)) .attr('method', getMethod(settings)) .attr('target', iframe.attr('name')); legacyUploadFormDataInit(input, form, settings); iframe.readyState = 2; form.get(0).submit(); legacyUploadFormDataReset(input, form, settings); form .attr('action', originalAction) .attr('method', originalMethod) .attr('target', originalTarget); }, handleLegacyUpload = function (event, input, form) { // javascript:false as iframe src prevents warning popups on HTTPS in IE6: var iframe = $('<iframe src="javascript:false;" style="display:none" name="iframe_' + settings.namespace + '_' + (new Date()).getTime() + '"></iframe>'), uploadSettings = $.extend({}, settings); uploadSettings.fileInput = input; uploadSettings.uploadForm = form; iframe.readyState = 0; iframe.abort = function () { iframe.trigger('abort'); }; iframe.bind('load', function () { iframe.unbind('load'); if (typeof uploadSettings.initUpload === func) { uploadSettings.initUpload( event, [{name: input.val(), type: null, size: null}], 0, iframe, uploadSettings, function () { legacyUpload(input, form, iframe, uploadSettings); } ); } else { legacyUpload(input, form, iframe, uploadSettings); } }).appendTo(form); }, initUploadForm = function () { uploadForm = (container.is('form') ? container : container.find('form')) .filter(settings.uploadFormFilter); }, initFileInput = function () { fileInput = uploadForm.find('input:file') .filter(settings.fileInputFilter); }, replaceFileInput = function (input) { var inputClone = input.clone(true); $('<form/>').append(inputClone).get(0).reset(); input.after(inputClone).detach(); initFileInput(); }; this.onDocumentDragOver = function (e) { if (typeof settings.onDocumentDragOver === func && settings.onDocumentDragOver(e) === false) { return false; } e.preventDefault(); }; this.onDocumentDrop = function (e) { if (typeof settings.onDocumentDrop === func && settings.onDocumentDrop(e) === false) { return false; } e.preventDefault(); }; this.onDragOver = function (e) { if (typeof settings.onDragOver === func && settings.onDragOver(e) === false) { return false; } var dataTransfer = e.originalEvent.dataTransfer; if (dataTransfer && dataTransfer.files) { dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy'; e.preventDefault(); } }; this.onDrop = function (e) { if (typeof settings.onDrop === func && settings.onDrop(e) === false) { return false; } var dataTransfer = e.originalEvent.dataTransfer; if (dataTransfer && dataTransfer.files && isXHRUploadCapable()) { handleFiles(e, dataTransfer.files); } e.preventDefault(); }; this.onChange = function (e) { if (typeof settings.onChange === func && settings.onChange(e) === false) { return false; } var input = $(e.target), form = $(e.target.form); if (form.length === 1) { input.data(defaultNamespace + '_form', form); replaceFileInput(input); } else { form = input.data(defaultNamespace + '_form'); } if (!settings.forceIframeUpload && e.target.files && isXHRUploadCapable()) { handleFiles(e, e.target.files, input, form); } else { handleLegacyUpload(e, input, form); } }; this.init = function (options) { if (options) { $.extend(settings, options); optionsReference = options; } initUploadForm(); initFileInput(); if (container.data(settings.namespace)) { $.error('FileUpload with namespace "' + settings.namespace + '" already assigned to this element'); return; } container .data(settings.namespace, fileUpload) .addClass(settings.cssClass); settings.dropZone.not(container).addClass(settings.cssClass); initEventHandlers(); }; this.options = function (options) { var oldCssClass, oldDropZone, uploadFormFilterUpdate, fileInputFilterUpdate; if (typeof options === undef) { return $.extend({}, settings); } if (optionsReference) { $.extend(optionsReference, options); } removeEventHandlers(); $.each(options, function (name, value) { switch (name) { case 'namespace': $.error('The FileUpload namespace cannot be updated.'); return; case 'uploadFormFilter': uploadFormFilterUpdate = true; fileInputFilterUpdate = true; break; case 'fileInputFilter': fileInputFilterUpdate = true; break; case 'cssClass': oldCssClass = settings.cssClass; break; case 'dropZone': oldDropZone = settings.dropZone; break; } settings[name] = value; }); if (uploadFormFilterUpdate) { initUploadForm(); } if (fileInputFilterUpdate) { initFileInput(); } if (typeof oldCssClass !== undef) { container .removeClass(oldCssClass) .addClass(settings.cssClass); (oldDropZone ? oldDropZone : settings.dropZone).not(container) .removeClass(oldCssClass); settings.dropZone.not(container).addClass(settings.cssClass); } else if (oldDropZone) { oldDropZone.not(container).removeClass(settings.cssClass); settings.dropZone.not(container).addClass(settings.cssClass); } initEventHandlers(); }; this.option = function (name, value) { var options; if (typeof value === undef) { return settings[name]; } options = {}; options[name] = value; fileUpload.options(options); }; this.destroy = function () { removeEventHandlers(); container .removeData(settings.namespace) .removeClass(settings.cssClass); settings.dropZone.not(container).removeClass(settings.cssClass); }; }; methods = { init : function (options) { return this.each(function () { (new FileUpload($(this))).init(options); }); }, option: function (option, value, namespace) { namespace = namespace ? namespace : defaultNamespace; var fileUpload = $(this).data(namespace); if (fileUpload) { if (typeof option === 'string') { return fileUpload.option(option, value); } return fileUpload.options(option); } else { $.error('No FileUpload with namespace "' + namespace + '" assigned to this element'); } }, destroy : function (namespace) { namespace = namespace ? namespace : defaultNamespace; return this.each(function () { var fileUpload = $(this).data(namespace); if (fileUpload) { fileUpload.destroy(); } else { $.error('No FileUpload with namespace "' + namespace + '" assigned to this element'); } }); } }; $.fn.fileUpload = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.fileUpload'); } }; }(jQuery));
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2015 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Phaser.Color class is a set of static methods that assist in color manipulation and conversion. * * @class Phaser.Color */ Phaser.Color = { /** * Packs the r, g, b, a components into a single integer, for use with Int32Array. * If device is little endian then ABGR order is used. Otherwise RGBA order is used. * * @author Matt DesLauriers (@mattdesl) * @method Phaser.Color.packPixel * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @param {number} a - The alpha color component, in the range 0 - 255. * @return {number} The packed color as uint32 */ packPixel: function (r, g, b, a) { if (Phaser.Device.LITTLE_ENDIAN) { return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0; } else { return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0; } }, /** * Unpacks the r, g, b, a components into the specified color object, or a new * object, for use with Int32Array. If little endian, then ABGR order is used when * unpacking, otherwise, RGBA order is used. The resulting color object has the * `r, g, b, a` properties which are unrelated to endianness. * * Note that the integer is assumed to be packed in the correct endianness. On little-endian * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a). * * @author Matt DesLauriers (@mattdesl) * @method Phaser.Color.unpackPixel * @static * @param {number} rgba - The integer, packed in endian order by packPixel. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl? * @param {boolean} [hsv=false] - Also convert the rgb values into hsv? * @return {object} An object with the red, green and blue values set in the r, g and b properties. */ unpackPixel: function (rgba, out, hsl, hsv) { if (out === undefined || out === null) { out = Phaser.Color.createColor(); } if (hsl === undefined || hsl === null) { hsl = false; } if (hsv === undefined || hsv === null) { hsv = false; } if (Phaser.Device.LITTLE_ENDIAN) { out.a = ((rgba & 0xff000000) >>> 24); out.b = ((rgba & 0x00ff0000) >>> 16); out.g = ((rgba & 0x0000ff00) >>> 8); out.r = ((rgba & 0x000000ff)); } else { out.r = ((rgba & 0xff000000) >>> 24); out.g = ((rgba & 0x00ff0000) >>> 16); out.b = ((rgba & 0x0000ff00) >>> 8); out.a = ((rgba & 0x000000ff)); } out.color = rgba; out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + (out.a / 255) + ')'; if (hsl) { Phaser.Color.RGBtoHSL(out.r, out.g, out.b, out); } if (hsv) { Phaser.Color.RGBtoHSV(out.r, out.g, out.b, out); } return out; }, /** * A utility to convert an integer in 0xRRGGBBAA format to a color object. * This does not rely on endianness. * * @author Matt DesLauriers (@mattdesl) * @method Phaser.Color.fromRGBA * @static * @param {number} rgba - An RGBA hex * @param {object} [out] - The object to use, optional. * @return {object} A color object. */ fromRGBA: function (rgba, out) { if (!out) { out = Phaser.Color.createColor(); } out.r = ((rgba & 0xff000000) >>> 24); out.g = ((rgba & 0x00ff0000) >>> 16); out.b = ((rgba & 0x0000ff00) >>> 8); out.a = ((rgba & 0x000000ff)); out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')'; return out; }, /** * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format. * * @author Matt DesLauriers (@mattdesl) * @method Phaser.Color.toRGBA * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @param {number} a - The alpha color component, in the range 0 - 255. * @return {number} A RGBA-packed 32 bit integer */ toRGBA: function (r, g, b, a) { return (r << 24) | (g << 16) | (b << 8) | a; }, /** * Converts an RGB color value to HSL (hue, saturation and lightness). * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1]. * Based on code by Michael Jackson (https://github.com/mjijackson) * * @method Phaser.Color.RGBtoHSL * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created. * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties. */ RGBtoHSL: function (r, g, b, out) { if (!out) { out = Phaser.Color.createColor(r, g, b, 1); } r /= 255; g /= 255; b /= 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); // achromatic by default out.h = 0; out.s = 0; out.l = (max + min) / 2; if (max !== min) { var d = max - min; out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min); if (max === r) { out.h = (g - b) / d + (g < b ? 6 : 0); } else if (max === g) { out.h = (b - r) / d + 2; } else if (max === b) { out.h = (r - g) / d + 4; } out.h /= 6; } return out; }, /** * Converts an HSL (hue, saturation and lightness) color value to RGB. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. * Based on code by Michael Jackson (https://github.com/mjijackson) * * @method Phaser.Color.HSLtoRGB * @static * @param {number} h - The hue, in the range 0 - 1. * @param {number} s - The saturation, in the range 0 - 1. * @param {number} l - The lightness, in the range 0 - 1. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. * @return {object} An object with the red, green and blue values set in the r, g and b properties. */ HSLtoRGB: function (h, s, l, out) { if (!out) { out = Phaser.Color.createColor(l, l, l); } else { // achromatic by default out.r = l; out.g = l; out.b = l; } if (s !== 0) { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3); out.g = Phaser.Color.hueToColor(p, q, h); out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3); } // out.r = (out.r * 255 | 0); // out.g = (out.g * 255 | 0); // out.b = (out.b * 255 | 0); out.r = Math.floor((out.r * 255 | 0)); out.g = Math.floor((out.g * 255 | 0)); out.b = Math.floor((out.b * 255 | 0)); Phaser.Color.updateColor(out); return out; }, /** * Converts an RGB color value to HSV (hue, saturation and value). * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1]. * Based on code by Michael Jackson (https://github.com/mjijackson) * * @method Phaser.Color.RGBtoHSV * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created. * @return {object} An object with the hue, saturation and value set in the h, s and v properties. */ RGBtoHSV: function (r, g, b, out) { if (!out) { out = Phaser.Color.createColor(r, g, b, 255); } r /= 255; g /= 255; b /= 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var d = max - min; // achromatic by default out.h = 0; out.s = max === 0 ? 0 : d / max; out.v = max; if (max !== min) { if (max === r) { out.h = (g - b) / d + (g < b ? 6 : 0); } else if (max === g) { out.h = (b - r) / d + 2; } else if (max === b) { out.h = (r - g) / d + 4; } out.h /= 6; } return out; }, /** * Converts an HSV (hue, saturation and value) color value to RGB. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255]. * Based on code by Michael Jackson (https://github.com/mjijackson) * * @method Phaser.Color.HSVtoRGB * @static * @param {number} h - The hue, in the range 0 - 1. * @param {number} s - The saturation, in the range 0 - 1. * @param {number} v - The value, in the range 0 - 1. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created. * @return {object} An object with the red, green and blue values set in the r, g and b properties. */ HSVtoRGB: function (h, s, v, out) { if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); } var r, g, b; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v; g = t; b = p; break; case 1: r = q; g = v; b = p; break; case 2: r = p; g = v; b = t; break; case 3: r = p; g = q; b = v; break; case 4: r = t; g = p; b = v; break; case 5: r = v; g = p; b = q; break; } out.r = Math.floor(r * 255); out.g = Math.floor(g * 255); out.b = Math.floor(b * 255); Phaser.Color.updateColor(out); return out; }, /** * Converts a hue to an RGB color. * Based on code by Michael Jackson (https://github.com/mjijackson) * * @method Phaser.Color.hueToColor * @static * @param {number} p * @param {number} q * @param {number} t * @return {number} The color component value. */ hueToColor: function (p, q, t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1 / 6) { return p + (q - p) * 6 * t; } if (t < 1 / 2) { return q; } if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6; } return p; }, /** * A utility function to create a lightweight 'color' object with the default components. * Any components that are not specified will default to zero. * * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods. * * @author Matt DesLauriers (@mattdesl) * @method Phaser.Color.createColor * @static * @param {number} [r=0] - The red color component, in the range 0 - 255. * @param {number} [g=0] - The green color component, in the range 0 - 255. * @param {number} [b=0] - The blue color component, in the range 0 - 255. * @param {number} [a=1] - The alpha color component, in the range 0 - 1. * @param {number} [h=0] - The hue, in the range 0 - 1. * @param {number} [s=0] - The saturation, in the range 0 - 1. * @param {number} [l=0] - The lightness, in the range 0 - 1. * @param {number} [v=0] - The value, in the range 0 - 1. * @return {object} The resulting object with r, g, b, a properties and h, s, l and v. */ createColor: function (r, g, b, a, h, s, l, v) { var out = { r: r || 0, g: g || 0, b: b || 0, a: a || 1, h: h || 0, s: s || 0, l: l || 0, v: v || 0, color: 0, color32: 0, rgba: '' }; return Phaser.Color.updateColor(out); }, /** * Takes a color object and updates the rgba property. * * @method Phaser.Color.updateColor * @static * @param {object} out - The color object to update. * @returns {number} A native color value integer (format: 0xAARRGGBB). */ updateColor: function (out) { out.rgba = 'rgba(' + out.r.toString() + ',' + out.g.toString() + ',' + out.b.toString() + ',' + out.a.toString() + ')'; out.color = Phaser.Color.getColor(out.r, out.g, out.b); out.color32 = Phaser.Color.getColor32(out.a, out.r, out.g, out.b); return out; }, /** * Given an alpha and 3 color values this will return an integer representation of it. * * @method Phaser.Color.getColor32 * @static * @param {number} a - The alpha color component, in the range 0 - 255. * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @returns {number} A native color value integer (format: 0xAARRGGBB). */ getColor32: function (a, r, g, b) { return a << 24 | r << 16 | g << 8 | b; }, /** * Given 3 color values this will return an integer representation of it. * * @method Phaser.Color.getColor * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @returns {number} A native color value integer (format: 0xRRGGBB). */ getColor: function (r, g, b) { return r << 16 | g << 8 | b; }, /** * Converts the given color values into a string. * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. * * @method Phaser.Color.RGBtoString * @static * @param {number} r - The red color component, in the range 0 - 255. * @param {number} g - The green color component, in the range 0 - 255. * @param {number} b - The blue color component, in the range 0 - 255. * @param {number} [a=255] - The alpha color component, in the range 0 - 255. * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`. * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`. */ RGBtoString: function (r, g, b, a, prefix) { if (a === undefined) { a = 255; } if (prefix === undefined) { prefix = '#'; } if (prefix === '#') { return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); } else { return '0x' + Phaser.Color.componentToHex(a) + Phaser.Color.componentToHex(r) + Phaser.Color.componentToHex(g) + Phaser.Color.componentToHex(b); } }, /** * Converts a hex string into an integer color value. * * @method Phaser.Color.hexToRGB * @static * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`. * @return {number} The rgb color value in the format 0xAARRGGBB. */ hexToRGB: function (hex) { var rgb = Phaser.Color.hexToColor(hex); if (rgb) { return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b); } }, /** * Converts a hex string into a Phaser Color object. * * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed. * * An alpha channel is _not_ supported. * * @method Phaser.Color.hexToColor * @static * @param {string} hex - The color string in a hex format. * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created. * @return {object} An object with the red, green and blue values set in the r, g and b properties. */ hexToColor: function (hex, out) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (result) { var r = parseInt(result[1], 16); var g = parseInt(result[2], 16); var b = parseInt(result[3], 16); if (!out) { out = Phaser.Color.createColor(r, g, b); } else { out.r = r; out.g = g; out.b = b; } } return out; }, /** * Converts a CSS 'web' string into a Phaser Color object. * * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1]. * * @method Phaser.Color.webToColor * @static * @param {string} web - The color string in CSS 'web' format. * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties. */ webToColor: function (web, out) { if (!out) { out = Phaser.Color.createColor(); } var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web); if (result) { out.r = parseInt(result[1], 10); out.g = parseInt(result[2], 10); out.b = parseInt(result[3], 10); out.a = result[4] !== undefined ? parseFloat(result[4]) : 1; Phaser.Color.updateColor(out); } return out; }, /** * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components. * * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`). * * An alpha channel is _not_ supported when specifying a hex string. * * @method Phaser.Color.valueToColor * @static * @param {string|number} value - The color expressed as a recognized string format or a packed integer. * @param {object} [out] - The object to use for the output. If not provided a new object will be created. * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties. */ valueToColor: function (value, out) { // The behavior is not consistent between hexToColor/webToColor on invalid input. // This unifies both by returning a new object, but returning null may be better. if (!out) { out = Phaser.Color.createColor(); } if (typeof value === 'string') { if (value.indexOf('rgb') === 0) { return Phaser.Color.webToColor(value, out); } else { // `hexToColor` does not support alpha; match `createColor`. out.a = 1; return Phaser.Color.hexToColor(value, out); } } else if (typeof value === 'number') { // `getRGB` does not take optional object to modify; // alpha is also adjusted to match `createColor`. var tempColor = Phaser.Color.getRGB(value); out.r = tempColor.r; out.g = tempColor.g; out.b = tempColor.b; out.a = tempColor.a / 255; return out; } else { return out; } }, /** * Return a string containing a hex representation of the given color component. * * @method Phaser.Color.componentToHex * @static * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255. * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64. */ componentToHex: function (color) { var hex = color.toString(16); return hex.length == 1 ? "0" + hex : hex; }, /** * Get HSV color wheel values in an array which will be 360 elements in size. * * @method Phaser.Color.HSVColorWheel * @static * @param {number} [s=1] - The saturation, in the range 0 - 1. * @param {number} [v=1] - The value, in the range 0 - 1. * @return {array} An array containing 360 elements corresponding to the HSV color wheel. */ HSVColorWheel: function (s, v) { if (s === undefined) { s = 1.0; } if (v === undefined) { v = 1.0; } var colors = []; for (var c = 0; c <= 359; c++) { colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v)); } return colors; }, /** * Get HSL color wheel values in an array which will be 360 elements in size. * * @method Phaser.Color.HSLColorWheel * @static * @param {number} [s=0.5] - The saturation, in the range 0 - 1. * @param {number} [l=0.5] - The lightness, in the range 0 - 1. * @return {array} An array containing 360 elements corresponding to the HSL color wheel. */ HSLColorWheel: function (s, l) { if (s === undefined) { s = 0.5; } if (l === undefined) { l = 0.5; } var colors = []; for (var c = 0; c <= 359; c++) { colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l)); } return colors; }, /** * Interpolates the two given colours based on the supplied step and currentStep properties. * * @method Phaser.Color.interpolateColor * @static * @param {number} color1 - The first color value. * @param {number} color2 - The second color value. * @param {number} steps - The number of steps to run the interpolation over. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. * @param {number} alpha - The alpha of the returned color. * @returns {number} The interpolated color value. */ interpolateColor: function (color1, color2, steps, currentStep, alpha) { if (alpha === undefined) { alpha = 255; } var src1 = Phaser.Color.getRGB(color1); var src2 = Phaser.Color.getRGB(color2); var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red; var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green; var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue; return Phaser.Color.getColor32(alpha, r, g, b); }, /** * Interpolates the two given colours based on the supplied step and currentStep properties. * * @method Phaser.Color.interpolateColorWithRGB * @static * @param {number} color - The first color value. * @param {number} r - The red color value, between 0 and 0xFF (255). * @param {number} g - The green color value, between 0 and 0xFF (255). * @param {number} b - The blue color value, between 0 and 0xFF (255). * @param {number} steps - The number of steps to run the interpolation over. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. * @returns {number} The interpolated color value. */ interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) { var src = Phaser.Color.getRGB(color); var or = (((r - src.red) * currentStep) / steps) + src.red; var og = (((g - src.green) * currentStep) / steps) + src.green; var ob = (((b - src.blue) * currentStep) / steps) + src.blue; return Phaser.Color.getColor(or, og, ob); }, /** * Interpolates the two given colours based on the supplied step and currentStep properties. * @method Phaser.Color.interpolateRGB * @static * @param {number} r1 - The red color value, between 0 and 0xFF (255). * @param {number} g1 - The green color value, between 0 and 0xFF (255). * @param {number} b1 - The blue color value, between 0 and 0xFF (255). * @param {number} r2 - The red color value, between 0 and 0xFF (255). * @param {number} g2 - The green color value, between 0 and 0xFF (255). * @param {number} b2 - The blue color value, between 0 and 0xFF (255). * @param {number} steps - The number of steps to run the interpolation over. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. * @returns {number} The interpolated color value. */ interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) { var r = (((r2 - r1) * currentStep) / steps) + r1; var g = (((g2 - g1) * currentStep) / steps) + g1; var b = (((b2 - b1) * currentStep) / steps) + b1; return Phaser.Color.getColor(r, g, b); }, /** * Returns a random color value between black and white * Set the min value to start each channel from the given offset. * Set the max value to restrict the maximum color used per channel. * * @method Phaser.Color.getRandomColor * @static * @param {number} [min=0] - The lowest value to use for the color. * @param {number} [max=255] - The highest value to use for the color. * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque). * @returns {number} 32-bit color value with alpha. */ getRandomColor: function (min, max, alpha) { if (min === undefined) { min = 0; } if (max === undefined) { max = 255; } if (alpha === undefined) { alpha = 255; } // Sanity checks if (max > 255 || min > max) { return Phaser.Color.getColor(255, 255, 255); } var red = min + Math.round(Math.random() * (max - min)); var green = min + Math.round(Math.random() * (max - min)); var blue = min + Math.round(Math.random() * (max - min)); return Phaser.Color.getColor32(alpha, red, green, blue); }, /** * Return the component parts of a color as an Object with the properties alpha, red, green, blue. * * Alpha will only be set if it exist in the given color (0xAARRGGBB) * * @method Phaser.Color.getRGB * @static * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given. */ getRGB: function (color) { if (color > 16777215) { // The color value has an alpha component return { alpha: color >>> 24, red: color >> 16 & 0xFF, green: color >> 8 & 0xFF, blue: color & 0xFF, a: color >>> 24, r: color >> 16 & 0xFF, g: color >> 8 & 0xFF, b: color & 0xFF }; } else { return { alpha: 255, red: color >> 16 & 0xFF, green: color >> 8 & 0xFF, blue: color & 0xFF, a: 255, r: color >> 16 & 0xFF, g: color >> 8 & 0xFF, b: color & 0xFF }; } }, /** * Returns a CSS friendly string value from the given color. * * @method Phaser.Color.getWebRGB * @static * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties. * @returns {string} A string in the format: 'rgba(r,g,b,a)' */ getWebRGB: function (color) { if (typeof color === 'object') { return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')'; } else { var rgb = Phaser.Color.getRGB(color); return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')'; } }, /** * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. * * @method Phaser.Color.getAlpha * @static * @param {number} color - In the format 0xAARRGGBB. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). */ getAlpha: function (color) { return color >>> 24; }, /** * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. * * @method Phaser.Color.getAlphaFloat * @static * @param {number} color - In the format 0xAARRGGBB. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). */ getAlphaFloat: function (color) { return (color >>> 24) / 255; }, /** * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. * * @method Phaser.Color.getRed * @static * @param {number} color In the format 0xAARRGGBB. * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). */ getRed: function (color) { return color >> 16 & 0xFF; }, /** * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. * * @method Phaser.Color.getGreen * @static * @param {number} color - In the format 0xAARRGGBB. * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). */ getGreen: function (color) { return color >> 8 & 0xFF; }, /** * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. * * @method Phaser.Color.getBlue * @static * @param {number} color - In the format 0xAARRGGBB. * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). */ getBlue: function (color) { return color & 0xFF; }, /** * Blends the source color, ignoring the backdrop. * * @method Phaser.Color.blendNormal * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendNormal: function (a) { return a; }, /** * Selects the lighter of the backdrop and source colors. * * @method Phaser.Color.blendLighten * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendLighten: function (a, b) { return (b > a) ? b : a; }, /** * Selects the darker of the backdrop and source colors. * * @method Phaser.Color.blendDarken * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendDarken: function (a, b) { return (b > a) ? a : b; }, /** * Multiplies the backdrop and source color values. * The result color is always at least as dark as either of the two constituent * colors. Multiplying any color with black produces black; * multiplying with white leaves the original color unchanged. * * @method Phaser.Color.blendMultiply * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendMultiply: function (a, b) { return (a * b) / 255; }, /** * Takes the average of the source and backdrop colors. * * @method Phaser.Color.blendAverage * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendAverage: function (a, b) { return (a + b) / 2; }, /** * Adds the source and backdrop colors together and returns the value, up to a maximum of 255. * * @method Phaser.Color.blendAdd * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendAdd: function (a, b) { return Math.min(255, a + b); }, /** * Combines the source and backdrop colors and returns their value minus 255. * * @method Phaser.Color.blendSubtract * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendSubtract: function (a, b) { return Math.max(0, a + b - 255); }, /** * Subtracts the darker of the two constituent colors from the lighter. * * Painting with white inverts the backdrop color; painting with black produces no change. * * @method Phaser.Color.blendDifference * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendDifference: function (a, b) { return Math.abs(a - b); }, /** * Negation blend mode. * * @method Phaser.Color.blendNegation * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendNegation: function (a, b) { return 255 - Math.abs(255 - a - b); }, /** * Multiplies the complements of the backdrop and source color values, then complements the result. * The result color is always at least as light as either of the two constituent colors. * Screening any color with white produces white; screening with black leaves the original color unchanged. * * @method Phaser.Color.blendScreen * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendScreen: function (a, b) { return 255 - (((255 - a) * (255 - b)) >> 8); }, /** * Produces an effect similar to that of the Difference mode, but lower in contrast. * Painting with white inverts the backdrop color; painting with black produces no change. * * @method Phaser.Color.blendExclusion * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendExclusion: function (a, b) { return a + b - 2 * a * b / 255; }, /** * Multiplies or screens the colors, depending on the backdrop color. * Source colors overlay the backdrop while preserving its highlights and shadows. * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop. * * @method Phaser.Color.blendOverlay * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendOverlay: function (a, b) { return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255); }, /** * Darkens or lightens the colors, depending on the source color value. * * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged; * this is useful for adding highlights to a scene. * * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in. * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; * if it is equal to 0.5, the backdrop is unchanged. * * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white. * The effect is similar to shining a diffused spotlight on the backdrop. * * @method Phaser.Color.blendSoftLight * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendSoftLight: function (a, b) { return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255); }, /** * Multiplies or screens the colors, depending on the source color value. * * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened; * this is useful for adding highlights to a scene. * * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied; * this is useful for adding shadows to a scene. * * The degree of lightening or darkening is proportional to the difference between the source color and 0.5; * if it is equal to 0.5, the backdrop is unchanged. * * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop. * * @method Phaser.Color.blendHardLight * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendHardLight: function (a, b) { return Phaser.Color.blendOverlay(b, a); }, /** * Brightens the backdrop color to reflect the source color. * Painting with black produces no change. * * @method Phaser.Color.blendColorDodge * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendColorDodge: function (a, b) { return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b))); }, /** * Darkens the backdrop color to reflect the source color. * Painting with white produces no change. * * @method Phaser.Color.blendColorBurn * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendColorBurn: function (a, b) { return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b)); }, /** * An alias for blendAdd, it simply sums the values of the two colors. * * @method Phaser.Color.blendLinearDodge * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendLinearDodge: function (a, b) { return Phaser.Color.blendAdd(a, b); }, /** * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255. * * @method Phaser.Color.blendLinearBurn * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendLinearBurn: function (a, b) { return Phaser.Color.blendSubtract(a, b); }, /** * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray). * Dodge applies to values of top layer lighter than middle gray, and burn to darker values. * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases. * * @method Phaser.Color.blendLinearLight * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendLinearLight: function (a, b) { return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128))); }, /** * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray). * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values. * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases. * * @method Phaser.Color.blendVividLight * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendVividLight: function (a, b) { return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128))); }, /** * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change. * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change. * * @method Phaser.Color.blendPinLight * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendPinLight: function (a, b) { return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128))); }, /** * Runs blendVividLight on the source and backdrop colors. * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0. * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255. * This changes all pixels to primary additive colors (red, green, or blue), white, or black. * * @method Phaser.Color.blendHardMix * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendHardMix: function (a, b) { return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255; }, /** * Reflect blend mode. This mode is useful when adding shining objects or light zones to images. * * @method Phaser.Color.blendReflect * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendReflect: function (a, b) { return b === 255 ? b : Math.min(255, (a * a / (255 - b))); }, /** * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped. * * @method Phaser.Color.blendGlow * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendGlow: function (a, b) { return Phaser.Color.blendReflect(b, a); }, /** * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result. * * @method Phaser.Color.blendPhoenix * @static * @param {integer} a - The source color to blend, in the range 1 to 255. * @param {integer} b - The backdrop color to blend, in the range 1 to 255. * @returns {integer} The blended color value, in the range 1 to 255. */ blendPhoenix: function (a, b) { return Math.min(a, b) - Math.max(a, b) + 255; } };
/*jshint node: true*/ /** * @module Bin:StartServer * @author kecso / https://github.com/kecso */ 'use strict'; var path = require('path'), gmeConfig = require(path.join(process.cwd(), 'config')), webgme = require('../../webgme'), myServer; webgme.addToRequireJsPaths(gmeConfig); myServer = new webgme.standaloneServer(gmeConfig); myServer.start(function (err) { if (err) { console.error(err); process.exit(1); } });
'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('tags');
Clazz.declarePackage ("javajs.swing"); Clazz.load (null, "javajs.swing.GridBagConstraints", ["javajs.swing.Insets"], function () { c$ = Clazz.decorateAsClass (function () { this.gridx = 0; this.gridy = 0; this.gridwidth = 0; this.gridheight = 0; this.weightx = 0; this.weighty = 0; this.anchor = 0; this.fill = 0; this.insets = null; this.ipadx = 0; this.ipady = 0; Clazz.instantialize (this, arguments); }, javajs.swing, "GridBagConstraints"); Clazz.makeConstructor (c$, function (gridx, gridy, gridwidth, gridheight, weightx, weighty, anchor, fill, insets, ipadx, ipady) { this.gridx = gridx; this.gridy = gridy; this.gridwidth = gridwidth; this.gridheight = gridheight; this.weightx = weightx; this.weighty = weighty; this.anchor = anchor; this.fill = fill; if (insets == null) insets = new javajs.swing.Insets (0, 0, 0, 0); this.insets = insets; this.ipadx = ipadx; this.ipady = ipady; }, "~N,~N,~N,~N,~N,~N,~N,~N,javajs.swing.Insets,~N,~N"); $_M(c$, "getStyle", function (margins) { return "style='" + (margins ? "margin:" + this.insets.top + "px " + (this.ipady + this.insets.right) + "px " + this.insets.bottom + "px " + (this.ipadx + this.insets.left) + "px;" : "text-align:" + (this.anchor == 13 ? "right" : this.anchor == 17 ? "left" : "center")) + "'"; }, "~B"); Clazz.defineStatics (c$, "NONE", 0, "CENTER", 10, "WEST", 17, "EAST", 13); });
const webpack = require("webpack"), WebpackDevServer = require("webpack-dev-server"), webpackConfig = require("./webpack.config") new WebpackDevServer(webpack(webpackConfig), { publicPath: "/static/", hot: true, historyApiFallback: true }) .listen(3000, "localhost", (err) => { if (err) console.log(err) console.log("Webpack listening at localhost:3000"); })
ace.define("ace/mode/json_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { "use strict"; var oop = acequire("../lib/oop"); var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; var JsonHighlightRules = function() { this.$rules = { "start" : [ { token : "variable", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)' }, { token : "string", // single line regex : '"', next : "string" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : "text", // single quoted strings are not allowed regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "comment", // comments are not allowed, but who cares? regex : "\\/\\/.*$" }, { token : "comment.start", // comments are not allowed, but who cares? regex : "\\/\\*", next : "comment" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "string" : [ { token : "constant.language.escape", regex : /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|["\\\/bfnrt])/ }, { token : "string", regex : '"|$', next : "start" }, { defaultToken : "string" } ], "comment" : [ { token : "comment.end", // comments are not allowed, but who cares? regex : "\\*\\/", next : "start" }, { defaultToken: "comment" } ] }; }; oop.inherits(JsonHighlightRules, TextHighlightRules); exports.JsonHighlightRules = JsonHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { "use strict"; var Range = acequire("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { "use strict"; var oop = acequire("../../lib/oop"); var Range = acequire("../../range").Range; var BaseFoldMode = acequire("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/worker/worker_client"], function(acequire, exports, module) { "use strict"; var oop = acequire("../lib/oop"); var TextMode = acequire("./text").Mode; var HighlightRules = acequire("./json_highlight_rules").JsonHighlightRules; var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; var WorkerClient = acequire("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = HighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], require("../worker/json"), "JsonWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/json"; }).call(Mode.prototype); exports.Mode = Mode; });
version https://git-lfs.github.com/spec/v1 oid sha256:edac9d30d529354e0f621640216b592c7d3917651071c818dd0292aa2760d7df size 9624
var __slice = Array.prototype.slice, Q = require('q'), _ = require('./lodash'), EventEmitter = require('events').EventEmitter, slice = Array.prototype.slice.call.bind(Array.prototype.slice), utils = require('./utils'); // The method below returns no result, so we are able hijack the result to // preserve the element scope. // This alows for thing like: field.click().clear().input('hello').getValue() var elementChainableMethods = ['clear','click','doubleClick','doubleclick', 'flick','sendKeys','submit','type','keys','moveTo','sleep','noop']; // gets the list of methods to be promisified. function filterPromisedMethods(Obj) { return _(Obj).functions().filter(function(fname) { return !fname.match('^newElement$|^toJSON$|^toString$|^_') && !EventEmitter.prototype[fname]; }).value(); } module.exports = function(WebDriver, Element, chainable) { // wraps element + browser call in an enriched promise. // This is the same as in the first promise version, but enrichment + // event logging were added. function wrap(fn, fname) { return function() { var _this = this; var callback; var args = slice(arguments); var deferred = Q.defer(); deferred.promise.then(function() { _this.emit("promise", _this, fname , args , "finished"); }); // Remove any undefined values from the end of the arguments array // as these interfere with our callback detection below for (var i = args.length - 1; i >= 0 && args[i] === undefined; i--) { args.pop(); } // If the last argument is a function assume that it's a callback // (Based on the API as of 2012/12/1 this assumption is always correct) if(typeof args[args.length - 1] === 'function') { // Remove to replace it with our callback and then call it // appropriately when the promise is resolved or rejected callback = args.pop(); deferred.promise.then(function(value) { callback(null, value); }, function(error) { callback(error); }); } args.push(deferred.makeNodeResolver()); _this.emit("promise", _this, fname , args , "calling"); fn.apply(this, args); if(chainable) { return this._enrich(deferred.promise); } else { return deferred.promise; } }; } // Element replacement. var PromiseElement = function() { var args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return Element.apply(this, args); }; PromiseElement.prototype = Object.create(Element.prototype); PromiseElement.prototype.isPromised = true; // WebDriver replacement. var PromiseWebdriver = function() { var args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return WebDriver.apply(this, args); }; PromiseWebdriver.prototype = Object.create(WebDriver.prototype); PromiseWebdriver.prototype.isPromised = true; PromiseWebdriver.prototype.defaultChainingScope = 'browser'; PromiseWebdriver.prototype.getDefaultChainingScope = function() { return this.defaultChainingScope; }; // wrapping browser methods with promises. _(filterPromisedMethods(WebDriver.prototype)).each(function(fname) { PromiseWebdriver.prototype[fname] = wrap(WebDriver.prototype[fname], fname); }); // wrapping element methods with promises. _(filterPromisedMethods(Element.prototype)).each(function(fname) { PromiseElement.prototype[fname] = wrap(Element.prototype[fname], fname); }); PromiseWebdriver.prototype.newElement = function(jsonWireElement) { return new PromiseElement(jsonWireElement, this); }; // enriches a promise with the browser + element methods. PromiseWebdriver.prototype._enrich = function(obj, currentEl) { var _this = this; // There are cases were enrich may be called on non-promise objects. // It is easier and safer to check within the method. if(utils.isPromise(obj) && !obj.__wd_promise_enriched) { var promise = obj; // __wd_promise_enriched is there to avoid enriching twice. promise.__wd_promise_enriched = true; // making sure all the sub-promises are also enriched. _(promise).functions().each(function(fname) { var _orig = promise[fname]; promise[fname] = function() { return this._enrich( _orig.apply(this, __slice.call(arguments, 0)), currentEl); }; }); // we get the list of methods dynamically. var promisedMethods = filterPromisedMethods(Object.getPrototypeOf(_this)); _this.sampleElement = _this.sampleElement || _this.newElement(1); var elementPromisedMethods = filterPromisedMethods(Object.getPrototypeOf(_this.sampleElement)); var allPromisedMethods = _.union(promisedMethods, elementPromisedMethods); // adding browser + element methods to the current promise. _(allPromisedMethods).each(function(fname) { promise[fname] = function() { var args = __slice.call(arguments, 0); // This is a hint to figure out if we need to call a browser method or // an element method. // "<" --> browser method // ">" --> element method var scopeHint; if(args && args[0] && typeof args[0] === 'string' && args[0].match(/^[<>]$/)) { scopeHint = args[0]; args = _.rest(args); } return this.then(function(res) { var el; // if the result is an element it has priority if(Element && res instanceof Element) { el = res; } // if we are within an element el = el || currentEl; // testing the water for the next call scope var isBrowserMethod = _.indexOf(promisedMethods, fname) >= 0; var isElementMethod = el && _.indexOf(elementPromisedMethods, fname) >= 0; if(!isBrowserMethod && !isElementMethod) { // doesn't look good throw new Error("Invalid method " + fname); } if(isBrowserMethod && isElementMethod) { // we need to resolve the conflict. if(scopeHint === '<') { isElementMethod = false; } else if(scopeHint === '>') { isBrowserMethod = false; } else if(fname.match(/element/) || (Element && args[0] instanceof Element)) { // method with element locators are browser scoped by default. if(_this.defaultChainingScope === 'element') { isBrowserMethod = false; } else { isElementMethod = false; } // default } else if(Element && args[0] instanceof Element) { // When an element is passed, we are in the global scope. isElementMethod = false; } else { // otherwise we stay in the element scope to allow sequential calls isBrowserMethod = false; } } if(isElementMethod) { // element method case. return el[fname].apply(el, args).then(function(res) { if(_.indexOf(elementChainableMethods, fname) >= 0) { // method like click, where no result is expected, we return // the element to make it chainable return el; } else { return res; // we have no choice but loosing the scope } }); }else{ // browser case. return _this[fname].apply(_this, args); } }); }; }); // transfering _enrich promise._enrich = function(target) { return _this._enrich(target, currentEl); }; // gets the element at index (starting at 0) promise.at = function(i) { return _this._enrich( promise.then(function(vals) { return vals[i]; }), currentEl); }; // gets the element at index (starting at 0) promise.last = function() { return promise.then(function(vals) { return vals[vals.length - 1]; }); }; // gets nth element (starting at 1) promise.nth = function(i) { return promise.at(i - 1); }; // gets the first element promise.first = function() { return promise.nth(1); }; // gets the first element promise.second = function() { return promise.nth(2); }; // gets the first element promise.third = function() { return promise.nth(3); }; // print error promise.printError = function(prepend) { prepend = prepend || ""; return _this._enrich( promise.catch(function(err) { console.log(prepend + err); throw err; }), currentEl); }; // print promise.print = function(prepend) { prepend = prepend || ""; return _this._enrich( promise.then(function(val) { console.log(prepend + val); }), currentEl); }; } return obj; }; /** * Starts the chain (promised driver only) * browser.chain() * element.chain() */ PromiseWebdriver.prototype.chain = PromiseWebdriver.prototype.noop; PromiseElement.prototype.chain = PromiseElement.prototype.noop; /** * Resolves the promise (promised driver only) * browser.resolve(promise) * element.resolve(promise) */ PromiseWebdriver.prototype.resolve = function(promise) { var qPromise = new Q(promise); this._enrich(qPromise); return qPromise; }; PromiseElement.prototype.resolve = function(promise) { var qPromise = new Q(promise); this._enrich(qPromise); return qPromise; }; // used to by chai-as-promised and custom methods PromiseElement.prototype._enrich = function(target) { if(chainable) { return this.browser._enrich(target, this); } }; // used to wrap custom methods PromiseWebdriver._wrapAsync = wrap; // helper to allow easier promise debugging. PromiseWebdriver.prototype._debugPromise = function() { this.on('promise', function(context, method, args, status) { args = _.clone(args); if(context instanceof PromiseWebdriver) { context = ''; } else { context = ' [element ' + context.value + ']'; } if(typeof _.last(args) === 'function') { args.pop(); } args = ' ( ' + _(args).map(function(arg) { if(arg instanceof Element) { return arg.toString(); } else if(typeof arg === 'object') { return JSON.stringify(arg); } else { return arg; } }).join(', ') + ' )'; console.log(' --> ' + status + context + " " + method + args); }); }; return { PromiseWebdriver: PromiseWebdriver, PromiseElement: PromiseElement }; };
var browse = require('./getBrowseData'), log = require('bole')('registry-browse-all-packages'); module.exports = function browseAll (skip, limit, next) { log.info('browse lookup: all ', skip, limit); return browse('all', false, skip, limit, next); };
define({ "_widgetLabel": "Análisis de incidentes", "_featureAction_SetAsIncident": "Establecer como incidente", "incident": "Incidente", "weather": "Tiempo", "locate_incident": "Localizar incidente", "clear_incidents": "Borrar incidentes", "reverse_geocoded_address": "Dirección más próxima", "reverse_geocoded_error": "No disponible", "miles": "Millas", "kilometers": "Kilómetros", "feet": "Pies", "meters": "Metros", "yards": "Yardas", "nauticalMiles": "Millas Náuticas", "now": "AHORA", "wind": "VIENTO", "SUN": "DOM", "MON": "LUN", "TUE": "MAR", "WED": "MIÉ", "THU": "JUE", "FRI": "VIE", "SAT": "SÁB", "defaultTabMsg": "No se han identificado incidentes.", "useMapExtent": "Usar la extensión del mapa actual", "noFeaturesFound": "No se encontraron entidades.", "downloadCSV": "DESCARGAR CSV", "sum": "SUM", "min": "MIN", "max": "MÁX", "avg": "AVG", "count": "TOTAL", "area": "ÁREA", "length": "LONGITUD" });
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.dialog.add("cellProperties",function(g){function d(a){return function(b){for(var c=a(b[0]),d=1;d<b.length;d++)if(a(b[d])!==c){c=null;break}"undefined"!=typeof c&&(this.setValue(c),CKEDITOR.env.gecko&&"select"==this.type&&!c&&(this.getInputElement().$.selectedIndex=-1))}}function l(a){if(a=n.exec(a.getStyle("width")||a.getAttribute("width")))return a[2]}var h=g.lang.table,c=h.cell,e=g.lang.common,k=CKEDITOR.dialog.validate,n=/^(\d+(?:\.\d+)?)(px|%)$/,f={type:"html",html:"\x26nbsp;"},p="rtl"== g.lang.dir,m=g.plugins.colordialog;return{title:c.title,minWidth:CKEDITOR.env.ie&&CKEDITOR.env.quirks?450:410,minHeight:CKEDITOR.env.ie&&(CKEDITOR.env.ie7Compat||CKEDITOR.env.quirks)?230:220,contents:[{id:"info",label:c.title,accessKey:"I",elements:[{type:"hbox",widths:["40%","5%","40%"],children:[{type:"vbox",padding:0,children:[{type:"hbox",widths:["70%","30%"],children:[{type:"text",id:"width",width:"100px",label:e.width,validate:k.number(c.invalidWidth),onLoad:function(){var a=this.getDialog().getContentElement("info", "widthType").getElement(),b=this.getInputElement(),c=b.getAttribute("aria-labelledby");b.setAttribute("aria-labelledby",[c,a.$.id].join(" "))},setup:d(function(a){var b=parseInt(a.getAttribute("width"),10);a=parseInt(a.getStyle("width"),10);return isNaN(a)?isNaN(b)?"":b:a}),commit:function(a){var b=parseInt(this.getValue(),10),c=this.getDialog().getValueOf("info","widthType")||l(a);isNaN(b)?a.removeStyle("width"):a.setStyle("width",b+c);a.removeAttribute("width")},"default":""},{type:"select",id:"widthType", label:g.lang.table.widthUnit,labelStyle:"visibility:hidden","default":"px",items:[[h.widthPx,"px"],[h.widthPc,"%"]],setup:d(l)}]},{type:"hbox",widths:["70%","30%"],children:[{type:"text",id:"height",label:e.height,width:"100px","default":"",validate:k.number(c.invalidHeight),onLoad:function(){var a=this.getDialog().getContentElement("info","htmlHeightType").getElement(),b=this.getInputElement(),c=b.getAttribute("aria-labelledby");b.setAttribute("aria-labelledby",[c,a.$.id].join(" "))},setup:d(function(a){var b= parseInt(a.getAttribute("height"),10);a=parseInt(a.getStyle("height"),10);return isNaN(a)?isNaN(b)?"":b:a}),commit:function(a){var b=parseInt(this.getValue(),10);isNaN(b)?a.removeStyle("height"):a.setStyle("height",CKEDITOR.tools.cssLength(b));a.removeAttribute("height")}},{id:"htmlHeightType",type:"html",html:"\x3cbr /\x3e"+h.widthPx}]},f,{type:"select",id:"wordWrap",label:c.wordWrap,"default":"yes",items:[[c.yes,"yes"],[c.no,"no"]],setup:d(function(a){var b=a.getAttribute("noWrap");if("nowrap"== a.getStyle("white-space")||b)return"no"}),commit:function(a){"no"==this.getValue()?a.setStyle("white-space","nowrap"):a.removeStyle("white-space");a.removeAttribute("noWrap")}},f,{type:"select",id:"hAlign",label:c.hAlign,"default":"",items:[[e.notSet,""],[e.alignLeft,"left"],[e.alignCenter,"center"],[e.alignRight,"right"],[e.alignJustify,"justify"]],setup:d(function(a){var b=a.getAttribute("align");return a.getStyle("text-align")||b||""}),commit:function(a){var b=this.getValue();b?a.setStyle("text-align", b):a.removeStyle("text-align");a.removeAttribute("align")}},{type:"select",id:"vAlign",label:c.vAlign,"default":"",items:[[e.notSet,""],[e.alignTop,"top"],[e.alignMiddle,"middle"],[e.alignBottom,"bottom"],[c.alignBaseline,"baseline"]],setup:d(function(a){var b=a.getAttribute("vAlign");a=a.getStyle("vertical-align");switch(a){case "top":case "middle":case "bottom":case "baseline":break;default:a=""}return a||b||""}),commit:function(a){var b=this.getValue();b?a.setStyle("vertical-align",b):a.removeStyle("vertical-align"); a.removeAttribute("vAlign")}}]},f,{type:"vbox",padding:0,children:[{type:"select",id:"cellType",label:c.cellType,"default":"td",items:[[c.data,"td"],[c.header,"th"]],setup:d(function(a){return a.getName()}),commit:function(a){a.renameNode(this.getValue())}},f,{type:"text",id:"rowSpan",label:c.rowSpan,"default":"",validate:k.integer(c.invalidRowSpan),setup:d(function(a){if((a=parseInt(a.getAttribute("rowSpan"),10))&&1!=a)return a}),commit:function(a){var b=parseInt(this.getValue(),10);b&&1!=b?a.setAttribute("rowSpan", this.getValue()):a.removeAttribute("rowSpan")}},{type:"text",id:"colSpan",label:c.colSpan,"default":"",validate:k.integer(c.invalidColSpan),setup:d(function(a){if((a=parseInt(a.getAttribute("colSpan"),10))&&1!=a)return a}),commit:function(a){var b=parseInt(this.getValue(),10);b&&1!=b?a.setAttribute("colSpan",this.getValue()):a.removeAttribute("colSpan")}},f,{type:"hbox",padding:0,widths:["60%","40%"],children:[{type:"text",id:"bgColor",label:c.bgColor,"default":"",setup:d(function(a){var b=a.getAttribute("bgColor"); return a.getStyle("background-color")||b}),commit:function(a){this.getValue()?a.setStyle("background-color",this.getValue()):a.removeStyle("background-color");a.removeAttribute("bgColor")}},m?{type:"button",id:"bgColorChoose","class":"colorChooser",label:c.chooseColor,onLoad:function(){this.getElement().getParent().setStyle("vertical-align","bottom")},onClick:function(){g.getColorFromDialog(function(a){a&&this.getDialog().getContentElement("info","bgColor").setValue(a);this.focus()},this)}}:f]},f, {type:"hbox",padding:0,widths:["60%","40%"],children:[{type:"text",id:"borderColor",label:c.borderColor,"default":"",setup:d(function(a){var b=a.getAttribute("borderColor");return a.getStyle("border-color")||b}),commit:function(a){this.getValue()?a.setStyle("border-color",this.getValue()):a.removeStyle("border-color");a.removeAttribute("borderColor")}},m?{type:"button",id:"borderColorChoose","class":"colorChooser",label:c.chooseColor,style:(p?"margin-right":"margin-left")+": 10px",onLoad:function(){this.getElement().getParent().setStyle("vertical-align", "bottom")},onClick:function(){g.getColorFromDialog(function(a){a&&this.getDialog().getContentElement("info","borderColor").setValue(a);this.focus()},this)}}:f]}]}]}]}],onShow:function(){this.cells=CKEDITOR.plugins.tabletools.getSelectedCells(this._.editor.getSelection());this.setupContent(this.cells)},onOk:function(){for(var a=this._.editor.getSelection(),b=a.createBookmarks(),c=this.cells,d=0;d<c.length;d++)this.commitContent(c[d]);this._.editor.forceNextSelectionCheck();a.selectBookmarks(b);this._.editor.selectionChange()}, onLoad:function(){var a={};this.foreach(function(b){b.setup&&b.commit&&(b.setup=CKEDITOR.tools.override(b.setup,function(c){return function(){c.apply(this,arguments);a[b.id]=b.getValue()}}),b.commit=CKEDITOR.tools.override(b.commit,function(c){return function(){a[b.id]!==b.getValue()&&c.apply(this,arguments)}}))})}}});
'use strict'; var deepDefaults = require('../lib/index'), assert = require('assert'); describe('deepDefaults()', function() { function expect(dest, src, expected) { it('deepDefaults(' + JSON.stringify(dest) + ', ' + JSON.stringify(src) + ') == ' + JSON.stringify(expected), function() { var actual = deepDefaults(dest, src); assert.deepEqual(actual, expected); assert.deepEqual(actual, dest); }); } expect({}, {}, {}); expect({}, undefined, {}); expect({}, null, {}); expect(undefined, undefined, undefined); expect(undefined, {}, undefined); expect(null, {}, null); expect(undefined, {a:1}, undefined); expect(null, {a:1}, null); expect({}, {a:1}, {a:1}); expect({a:1}, {a:1}, {a:1}); expect({a:2}, {a:1}, {a:2}); expect({a:2}, {a:null}, {a:2}); expect({a:2}, {a:undefined}, {a:2}); expect({a:2}, {a:{}}, {a:2}); expect({a:{}}, {a:1}, {a:{}}); expect({a:null}, {a:1}, {a:null}); expect({a:undefined}, {a:1}, {a:1}); expect({a:2, b:1}, {a:1}, {a:2, b:1}); expect({a:2, b:1}, {b:2}, {a:2, b:1}); expect({a:2, b:1}, {a:1, b:2}, {a:2, b:1}); expect({a:2, b:1}, {a:1, b:2, c:3}, {a:2, b:1, c:3}); expect({a:{b:1}}, {}, {a:{b:1}}); expect({a:{b:1}}, {a:1}, {a:{b:1}}); expect({a:{b:1}}, {b:2}, {a:{b:1}, b:2}); expect({a:{b:1, c:3}}, {b:2}, {a:{b:1, c:3}, b:2}); expect({a:{b:1, c:3}}, {a:{}}, {a:{b:1, c:3}}); expect({a:{b:1, c:3}}, {a:{b:2}}, {a:{b:1, c:3}}); expect({a:{b:1, c:3}}, {a:{d:4}}, {a:{b:1, c:3, d:4}}); expect({a:{}}, {a:{d:4}}, {a:{d:4}}); expect({a:{b:1, c:2}, d:{e:3, f:4}, g:5}, {}, {a:{b:1, c:2}, d:{e:3, f:4}, g:5}); expect({a:{b:1, c:2}, d:{e:3, f:4}, g:5}, {h:6}, {a:{b:1, c:2}, d:{e:3, f:4}, g:5, h:6}); expect({a:{b:1, c:2}, d:{e:3, f:4}, g:5}, {a:6}, {a:{b:1, c:2}, d:{e:3, f:4}, g:5}); expect({a:{b:1, c:2}, d:{e:3, f:4}, g:5}, {a:{k:7}}, {a:{b:1, c:2, k:7}, d:{e:3, f:4}, g:5}); expect({a:{b:1, c:2}, d:{e:3, f:4}, g:5}, {a:{k:7}, d:{i:8}}, {a:{b:1, c:2, k:7}, d:{e:3, f:4, i:8}, g:5}); expect({foo:'foo'}, {foo:'foo'}, {foo:'foo'}); expect({foo:'foo'}, {}, {foo:'foo'}); expect({}, {foo:'foo'}, {foo:'foo'}); expect({foo:7}, {foo:'foo'}, {foo:7}); expect({foo:'foo'}, {foo:7}, {foo:'foo'}); expect({foo:{}}, {foo:'foo'}, {foo:{}}); expect({foo:{bar:7}}, {foo:'foo'}, {foo:{bar:7}}); expect({foo:{bar:'foobar'}}, {foo:'barfoo'}, {foo:{bar:'foobar'}}); expect({foo:'barfoo'}, {foo:{bar:'foobar'}}, {foo:'barfoo'}); // arrays are not merged expect({}, {foo: [4,5,6]}, {foo: [4,5,6]}); expect({foo: [1,2,3]}, {foo: [4,5,6]}, {foo: [1,2,3]}); expect({foo: [1,2,3]}, {foo: 'bar'}, {foo: [1,2,3]}); expect({foo: [1,2,3]}, {foo: [1,2,3,4]}, {foo: [1,2,3]}); });
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('single'); this.route('multiple'); this.route('zany-embedded-html'); }); export default Router;
// Last time updated: 2017-04-29 7:05:22 AM UTC // Latest file can be found here: https://cdn.webrtc-experiment.com/DetectRTC.js // Muaz Khan - www.MuazKhan.com // MIT License - www.WebRTC-Experiment.com/licence // Documentation - github.com/muaz-khan/DetectRTC // ____________ // DetectRTC.js // DetectRTC.hasWebcam (has webcam device!) // DetectRTC.hasMicrophone (has microphone device!) // DetectRTC.hasSpeakers (has speakers!) (function() { 'use strict'; var browserFakeUserAgent = 'Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45'; var isNodejs = typeof process === 'object' && typeof process.versions === 'object' && process.versions.node; if (isNodejs) { var version = process.versions.node.toString().replace('v', ''); browserFakeUserAgent = 'Nodejs/' + version + ' (NodeOS) AppleWebKit/' + version + ' (KHTML, like Gecko) Nodejs/' + version + ' Nodejs/' + version } (function(that) { if (typeof window !== 'undefined') { return; } if (typeof window === 'undefined' && typeof global !== 'undefined') { global.navigator = { userAgent: browserFakeUserAgent, getUserMedia: function() {} }; /*global window:true */ that.window = global; } else if (typeof window === 'undefined') { // window = this; } if (typeof document === 'undefined') { /*global document:true */ that.document = {}; document.createElement = document.captureStream = document.mozCaptureStream = function() { return {}; }; } if (typeof location === 'undefined') { /*global location:true */ that.location = { protocol: 'file:', href: '', hash: '' }; } if (typeof screen === 'undefined') { /*global screen:true */ that.screen = { width: 0, height: 0 }; } })(typeof global !== 'undefined' ? global : window); /*global navigator:true */ var navigator = window.navigator; if (typeof navigator !== 'undefined') { if (typeof navigator.webkitGetUserMedia !== 'undefined') { navigator.getUserMedia = navigator.webkitGetUserMedia; } if (typeof navigator.mozGetUserMedia !== 'undefined') { navigator.getUserMedia = navigator.mozGetUserMedia; } } else { navigator = { getUserMedia: function() {}, userAgent: browserFakeUserAgent }; } var isMobileDevice = !!(/Android|webOS|iPhone|iPad|iPod|BB10|BlackBerry|IEMobile|Opera Mini|Mobile|mobile/i.test(navigator.userAgent || '')); var isEdge = navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveOrOpenBlob || !!navigator.msSaveBlob); var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; var isFirefox = typeof window.InstallTrigger !== 'undefined'; var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; var isChrome = !!window.chrome && !isOpera; var isIE = !!document.documentMode && !isEdge; // this one can also be used: // https://www.websocket.org/js/stuff.js (DetectBrowser.js) function getBrowserInfo() { var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var browserName = navigator.appName; var fullVersion = '' + parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion, 10); var nameOffset, verOffset, ix; // In Opera, the true version is after 'Opera' or after 'Version' if (isOpera) { browserName = 'Opera'; try { fullVersion = navigator.userAgent.split('OPR/')[1].split(' ')[0]; majorVersion = fullVersion.split('.')[0]; } catch (e) { fullVersion = '0.0.0.0'; majorVersion = 0; } } // In MSIE, the true version is after 'MSIE' in userAgent else if (isIE) { verOffset = nAgt.indexOf('MSIE'); browserName = 'IE'; fullVersion = nAgt.substring(verOffset + 5); } // In Chrome, the true version is after 'Chrome' else if (isChrome) { verOffset = nAgt.indexOf('Chrome'); browserName = 'Chrome'; fullVersion = nAgt.substring(verOffset + 7); } // In Safari, the true version is after 'Safari' or after 'Version' else if (isSafari) { verOffset = nAgt.indexOf('Safari'); browserName = 'Safari'; fullVersion = nAgt.substring(verOffset + 7); if ((verOffset = nAgt.indexOf('Version')) !== -1) { fullVersion = nAgt.substring(verOffset + 8); } } // In Firefox, the true version is after 'Firefox' else if (isFirefox) { verOffset = nAgt.indexOf('Firefox'); browserName = 'Firefox'; fullVersion = nAgt.substring(verOffset + 8); } // In most other browsers, 'name/version' is at the end of userAgent else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) { browserName = nAgt.substring(nameOffset, verOffset); fullVersion = nAgt.substring(verOffset + 1); if (browserName.toLowerCase() === browserName.toUpperCase()) { browserName = navigator.appName; } } if (isEdge) { browserName = 'Edge'; // fullVersion = navigator.userAgent.split('Edge/')[1]; fullVersion = parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10).toString(); } // trim the fullVersion string at semicolon/space if present if ((ix = fullVersion.indexOf(';')) !== -1) { fullVersion = fullVersion.substring(0, ix); } if ((ix = fullVersion.indexOf(' ')) !== -1) { fullVersion = fullVersion.substring(0, ix); } majorVersion = parseInt('' + fullVersion, 10); if (isNaN(majorVersion)) { fullVersion = '' + parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion, 10); } return { fullVersion: fullVersion, version: majorVersion, name: browserName, isPrivateBrowsing: false }; } // via: https://gist.github.com/cou929/7973956 function retry(isDone, next) { var currentTrial = 0, maxRetry = 50, interval = 10, isTimeout = false; var id = window.setInterval( function() { if (isDone()) { window.clearInterval(id); next(isTimeout); } if (currentTrial++ > maxRetry) { window.clearInterval(id); isTimeout = true; next(isTimeout); } }, 10 ); } function isIE10OrLater(userAgent) { var ua = userAgent.toLowerCase(); if (ua.indexOf('msie') === 0 && ua.indexOf('trident') === 0) { return false; } var match = /(?:msie|rv:)\s?([\d\.]+)/.exec(ua); if (match && parseInt(match[1], 10) >= 10) { return true; } return false; } function detectPrivateMode(callback) { var isPrivate; try { if (window.webkitRequestFileSystem) { window.webkitRequestFileSystem( window.TEMPORARY, 1, function() { isPrivate = false; }, function(e) { isPrivate = true; } ); } else if (window.indexedDB && /Firefox/.test(window.navigator.userAgent)) { var db; try { db = window.indexedDB.open('test'); db.onerror = function() { return true; }; } catch (e) { isPrivate = true; } if (typeof isPrivate === 'undefined') { retry( function isDone() { return db.readyState === 'done' ? true : false; }, function next(isTimeout) { if (!isTimeout) { isPrivate = db.result ? false : true; } } ); } } else if (isIE10OrLater(window.navigator.userAgent)) { isPrivate = false; try { if (!window.indexedDB) { isPrivate = true; } } catch (e) { isPrivate = true; } } else if (window.localStorage && /Safari/.test(window.navigator.userAgent)) { try { window.localStorage.setItem('test', 1); } catch (e) { isPrivate = true; } if (typeof isPrivate === 'undefined') { isPrivate = false; window.localStorage.removeItem('test'); } } } catch (e) { isPrivate = false; } retry( function isDone() { return typeof isPrivate !== 'undefined' ? true : false; }, function next(isTimeout) { callback(isPrivate); } ); } var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry|BB10/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); }, getOsName: function() { var osName = 'Unknown OS'; if (isMobile.Android()) { osName = 'Android'; } if (isMobile.BlackBerry()) { osName = 'BlackBerry'; } if (isMobile.iOS()) { osName = 'iOS'; } if (isMobile.Opera()) { osName = 'Opera Mini'; } if (isMobile.Windows()) { osName = 'Windows'; } return osName; } }; // via: http://jsfiddle.net/ChristianL/AVyND/ function detectDesktopOS() { var unknown = '-'; var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var os = unknown; var clientStrings = [{ s: 'Windows 10', r: /(Windows 10.0|Windows NT 10.0)/ }, { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ }, { s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ }, { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ }, { s: 'Windows Vista', r: /Windows NT 6.0/ }, { s: 'Windows Server 2003', r: /Windows NT 5.2/ }, { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ }, { s: 'Windows 2000', r: /(Windows NT 5.0|Windows 2000)/ }, { s: 'Windows ME', r: /(Win 9x 4.90|Windows ME)/ }, { s: 'Windows 98', r: /(Windows 98|Win98)/ }, { s: 'Windows 95', r: /(Windows 95|Win95|Windows_95)/ }, { s: 'Windows NT 4.0', r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ }, { s: 'Windows CE', r: /Windows CE/ }, { s: 'Windows 3.11', r: /Win16/ }, { s: 'Android', r: /Android/ }, { s: 'Open BSD', r: /OpenBSD/ }, { s: 'Sun OS', r: /SunOS/ }, { s: 'Linux', r: /(Linux|X11)/ }, { s: 'iOS', r: /(iPhone|iPad|iPod)/ }, { s: 'Mac OS X', r: /Mac OS X/ }, { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ }, { s: 'QNX', r: /QNX/ }, { s: 'UNIX', r: /UNIX/ }, { s: 'BeOS', r: /BeOS/ }, { s: 'OS/2', r: /OS\/2/ }, { s: 'Search Bot', r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/ }]; for (var i = 0, cs; cs = clientStrings[i]; i++) { if (cs.r.test(nAgt)) { os = cs.s; break; } } var osVersion = unknown; if (/Windows/.test(os)) { if (/Windows (.*)/.test(os)) { osVersion = /Windows (.*)/.exec(os)[1]; } os = 'Windows'; } switch (os) { case 'Mac OS X': if (/Mac OS X (10[\.\_\d]+)/.test(nAgt)) { osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1]; } break; case 'Android': if (/Android ([\.\_\d]+)/.test(nAgt)) { osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1]; } break; case 'iOS': if (/OS (\d+)_(\d+)_?(\d+)?/.test(nAgt)) { osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer); osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0); } break; } return { osName: os, osVersion: osVersion }; } var osName = 'Unknown OS'; var osVersion = 'Unknown OS Version'; function getAndroidVersion(ua) { ua = (ua || navigator.userAgent).toLowerCase(); var match = ua.match(/android\s([0-9\.]*)/); return match ? match[1] : false; } var osInfo = detectDesktopOS(); if (osInfo && osInfo.osName && osInfo.osName != '-') { osName = osInfo.osName; osVersion = osInfo.osVersion; } else if (isMobile.any()) { osName = isMobile.getOsName(); if (osName == 'Android') { osVersion = getAndroidVersion(); } } var isNodejs = typeof process === 'object' && typeof process.versions === 'object' && process.versions.node; if (osName === 'Unknown OS' && isNodejs) { osName = 'Nodejs'; osVersion = process.versions.node.toString().replace('v', ''); } var isCanvasSupportsStreamCapturing = false; var isVideoSupportsStreamCapturing = false; ['captureStream', 'mozCaptureStream', 'webkitCaptureStream'].forEach(function(item) { if (!isCanvasSupportsStreamCapturing && item in document.createElement('canvas')) { isCanvasSupportsStreamCapturing = true; } if (!isVideoSupportsStreamCapturing && item in document.createElement('video')) { isVideoSupportsStreamCapturing = true; } }); // via: https://github.com/diafygi/webrtc-ips function DetectLocalIPAddress(callback) { if (!DetectRTC.isWebRTCSupported) { return; } if (DetectRTC.isORTCSupported) { return; } getIPs(function(ip) { //local IPs if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) { callback('Local: ' + ip); } //assume the rest are public IPs else { callback('Public: ' + ip); } }); } //get the IP addresses associated with an account function getIPs(callback) { var ipDuplicates = {}; //compatibility for firefox and chrome var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var useWebKit = !!window.webkitRTCPeerConnection; // bypass naive webrtc blocking using an iframe if (!RTCPeerConnection) { var iframe = document.getElementById('iframe'); if (!iframe) { //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe> throw 'NOTE: you need to have an iframe in the page right above the script tag.'; } var win = iframe.contentWindow; RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection; useWebKit = !!win.webkitRTCPeerConnection; } // if still no RTCPeerConnection then it is not supported by the browser so just return if (!RTCPeerConnection) { return; } //minimal requirements for data connection var mediaConstraints = { optional: [{ RtpDataChannels: true }] }; //firefox already has a default stun server in about:config // media.peerconnection.default_iceservers = // [{"url": "stun:stun.services.mozilla.com"}] var servers; //add same stun server for chrome if (useWebKit) { servers = { iceServers: [{ urls: 'stun:stun.services.mozilla.com' }] }; if (typeof DetectRTC !== 'undefined' && DetectRTC.browser.isFirefox && DetectRTC.browser.version <= 38) { servers[0] = { url: servers[0].urls }; } } //construct a new RTCPeerConnection var pc = new RTCPeerConnection(servers, mediaConstraints); function handleCandidate(candidate) { //match just the IP address var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/; var match = ipRegex.exec(candidate); if (!match) { console.warn('Could not match IP address in', candidate); return; } var ipAddress = match[1]; //remove duplicates if (ipDuplicates[ipAddress] === undefined) { callback(ipAddress); } ipDuplicates[ipAddress] = true; } //listen for candidate events pc.onicecandidate = function(ice) { //skip non-candidate events if (ice.candidate) { handleCandidate(ice.candidate.candidate); } }; //create a bogus data channel pc.createDataChannel(''); //create an offer sdp pc.createOffer(function(result) { //trigger the stun server request pc.setLocalDescription(result, function() {}, function() {}); }, function() {}); //wait for a while to let everything done setTimeout(function() { //read candidate info from local description var lines = pc.localDescription.sdp.split('\n'); lines.forEach(function(line) { if (line.indexOf('a=candidate:') === 0) { handleCandidate(line); } }); }, 1000); } var MediaDevices = []; var audioInputDevices = []; var audioOutputDevices = []; var videoInputDevices = []; if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) { // Firefox 38+ seems having support of enumerateDevices // Thanks @xdumaine/enumerateDevices navigator.enumerateDevices = function(callback) { navigator.mediaDevices.enumerateDevices().then(callback).catch(function() { callback([]); }); }; } // Media Devices detection var canEnumerate = false; /*global MediaStreamTrack:true */ if (typeof MediaStreamTrack !== 'undefined' && 'getSources' in MediaStreamTrack) { canEnumerate = true; } else if (navigator.mediaDevices && !!navigator.mediaDevices.enumerateDevices) { canEnumerate = true; } var hasMicrophone = false; var hasSpeakers = false; var hasWebcam = false; var isWebsiteHasMicrophonePermissions = false; var isWebsiteHasWebcamPermissions = false; // http://dev.w3.org/2011/webrtc/editor/getusermedia.html#mediadevices function checkDeviceSupport(callback) { if (!canEnumerate) { if (callback) { callback(); } return; } if (!navigator.enumerateDevices && window.MediaStreamTrack && window.MediaStreamTrack.getSources) { navigator.enumerateDevices = window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack); } if (!navigator.enumerateDevices && navigator.enumerateDevices) { navigator.enumerateDevices = navigator.enumerateDevices.bind(navigator); } if (!navigator.enumerateDevices) { if (callback) { callback(); } return; } MediaDevices = []; audioInputDevices = []; audioOutputDevices = []; videoInputDevices = []; isWebsiteHasMicrophonePermissions = false; isWebsiteHasWebcamPermissions = false; // to prevent duplication var alreadyUsedDevices = {}; navigator.enumerateDevices(function(devices) { devices.forEach(function(_device) { var device = {}; for (var d in _device) { try { if (typeof _device[d] !== 'function') { device[d] = _device[d]; } } catch (e) {} } if (alreadyUsedDevices[device.deviceId + device.label]) { return; } // if it is MediaStreamTrack.getSources if (device.kind === 'audio') { device.kind = 'audioinput'; } if (device.kind === 'video') { device.kind = 'videoinput'; } if (!device.deviceId) { device.deviceId = device.id; } if (!device.id) { device.id = device.deviceId; } if (!device.label) { device.label = 'Please invoke getUserMedia once.'; if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 46 && !/^(https:|chrome-extension:)$/g.test(location.protocol || '')) { if (document.domain.search && document.domain.search(/localhost|127.0./g) === -1) { device.label = 'HTTPs is required to get label of this ' + device.kind + ' device.'; } } } else { if (device.kind === 'videoinput' && !isWebsiteHasWebcamPermissions) { isWebsiteHasWebcamPermissions = true; } if (device.kind === 'audioinput' && !isWebsiteHasMicrophonePermissions) { isWebsiteHasMicrophonePermissions = true; } } if (device.kind === 'audioinput') { hasMicrophone = true; if (audioInputDevices.indexOf(device) === -1) { audioInputDevices.push(device); } } if (device.kind === 'audiooutput') { hasSpeakers = true; if (audioOutputDevices.indexOf(device) === -1) { audioOutputDevices.push(device); } } if (device.kind === 'videoinput') { hasWebcam = true; if (videoInputDevices.indexOf(device) === -1) { videoInputDevices.push(device); } } // there is no 'videoouput' in the spec. MediaDevices.push(device); alreadyUsedDevices[device.deviceId + device.label] = device; }); if (typeof DetectRTC !== 'undefined') { // to sync latest outputs DetectRTC.MediaDevices = MediaDevices; DetectRTC.hasMicrophone = hasMicrophone; DetectRTC.hasSpeakers = hasSpeakers; DetectRTC.hasWebcam = hasWebcam; DetectRTC.isWebsiteHasWebcamPermissions = isWebsiteHasWebcamPermissions; DetectRTC.isWebsiteHasMicrophonePermissions = isWebsiteHasMicrophonePermissions; DetectRTC.audioInputDevices = audioInputDevices; DetectRTC.audioOutputDevices = audioOutputDevices; DetectRTC.videoInputDevices = videoInputDevices; } if (callback) { callback(); } }); } // check for microphone/camera support! checkDeviceSupport(); var DetectRTC = window.DetectRTC || {}; // ---------- // DetectRTC.browser.name || DetectRTC.browser.version || DetectRTC.browser.fullVersion DetectRTC.browser = getBrowserInfo(); detectPrivateMode(function(isPrivateBrowsing) { DetectRTC.browser.isPrivateBrowsing = !!isPrivateBrowsing; }); // DetectRTC.isChrome || DetectRTC.isFirefox || DetectRTC.isEdge DetectRTC.browser['is' + DetectRTC.browser.name] = true; // ----------- DetectRTC.osName = osName; DetectRTC.osVersion = osVersion; var isNodeWebkit = typeof process === 'object' && typeof process.versions === 'object' && process.versions['node-webkit']; // --------- Detect if system supports WebRTC 1.0 or WebRTC 1.1. var isWebRTCSupported = false; ['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection', 'RTCIceGatherer'].forEach(function(item) { if (isWebRTCSupported) { return; } if (item in window) { isWebRTCSupported = true; } }); DetectRTC.isWebRTCSupported = isWebRTCSupported; //------- DetectRTC.isORTCSupported = typeof RTCIceGatherer !== 'undefined'; // --------- Detect if system supports screen capturing API var isScreenCapturingSupported = false; if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 35) { isScreenCapturingSupported = true; } else if (DetectRTC.browser.isFirefox && DetectRTC.browser.version >= 34) { isScreenCapturingSupported = true; } if (!/^(https:|chrome-extension:)$/g.test(location.protocol || '')) { if (document.domain.search && document.domain.search(/localhost|127.0./g) === -1) { // DetectRTC.browser.isChrome isScreenCapturingSupported = false; } if (DetectRTC.browser.isFirefox) { isScreenCapturingSupported = false; } } DetectRTC.isScreenCapturingSupported = isScreenCapturingSupported; // --------- Detect if WebAudio API are supported var webAudio = { isSupported: false, isCreateMediaStreamSourceSupported: false }; ['AudioContext', 'webkitAudioContext', 'mozAudioContext', 'msAudioContext'].forEach(function(item) { if (webAudio.isSupported) { return; } if (item in window) { webAudio.isSupported = true; if (window[item] && 'createMediaStreamSource' in window[item].prototype) { webAudio.isCreateMediaStreamSourceSupported = true; } } }); DetectRTC.isAudioContextSupported = webAudio.isSupported; DetectRTC.isCreateMediaStreamSourceSupported = webAudio.isCreateMediaStreamSourceSupported; // ---------- Detect if SCTP/RTP channels are supported. var isRtpDataChannelsSupported = false; if (DetectRTC.browser.isChrome && DetectRTC.browser.version > 31) { isRtpDataChannelsSupported = true; } DetectRTC.isRtpDataChannelsSupported = isRtpDataChannelsSupported; var isSCTPSupportd = false; if (DetectRTC.browser.isFirefox && DetectRTC.browser.version > 28) { isSCTPSupportd = true; } else if (DetectRTC.browser.isChrome && DetectRTC.browser.version > 25) { isSCTPSupportd = true; } else if (DetectRTC.browser.isOpera && DetectRTC.browser.version >= 11) { isSCTPSupportd = true; } DetectRTC.isSctpDataChannelsSupported = isSCTPSupportd; // --------- DetectRTC.isMobileDevice = isMobileDevice; // "isMobileDevice" boolean is defined in "getBrowserInfo.js" // ------ var isGetUserMediaSupported = false; if (navigator.getUserMedia) { isGetUserMediaSupported = true; } else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { isGetUserMediaSupported = true; } if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 46 && !/^(https:|chrome-extension:)$/g.test(location.protocol || '')) { if (document.domain.search && document.domain.search(/localhost|127.0./g) === -1) { isGetUserMediaSupported = 'Requires HTTPs'; } } if (DetectRTC.osName === 'Nodejs') { isGetUserMediaSupported = false; } DetectRTC.isGetUserMediaSupported = isGetUserMediaSupported; var displayResolution = ''; if (screen.width) { var width = (screen.width) ? screen.width : ''; var height = (screen.height) ? screen.height : ''; displayResolution += '' + width + ' x ' + height; } DetectRTC.displayResolution = displayResolution; // ---------- DetectRTC.isCanvasSupportsStreamCapturing = isCanvasSupportsStreamCapturing; DetectRTC.isVideoSupportsStreamCapturing = isVideoSupportsStreamCapturing; if (DetectRTC.browser.name == 'Chrome' && DetectRTC.browser.version >= 53) { if (!DetectRTC.isCanvasSupportsStreamCapturing) { DetectRTC.isCanvasSupportsStreamCapturing = 'Requires chrome flag: enable-experimental-web-platform-features'; } if (!DetectRTC.isVideoSupportsStreamCapturing) { DetectRTC.isVideoSupportsStreamCapturing = 'Requires chrome flag: enable-experimental-web-platform-features'; } } // ------ DetectRTC.DetectLocalIPAddress = DetectLocalIPAddress; DetectRTC.isWebSocketsSupported = 'WebSocket' in window && 2 === window.WebSocket.CLOSING; DetectRTC.isWebSocketsBlocked = !DetectRTC.isWebSocketsSupported; if (DetectRTC.osName === 'Nodejs') { DetectRTC.isWebSocketsSupported = true; DetectRTC.isWebSocketsBlocked = false; } DetectRTC.checkWebSocketsSupport = function(callback) { callback = callback || function() {}; try { var websocket = new WebSocket('wss://echo.websocket.org:443/'); websocket.onopen = function() { DetectRTC.isWebSocketsBlocked = false; callback(); websocket.close(); websocket = null; }; websocket.onerror = function() { DetectRTC.isWebSocketsBlocked = true; callback(); }; } catch (e) { DetectRTC.isWebSocketsBlocked = true; callback(); } }; // ------- DetectRTC.load = function(callback) { callback = callback || function() {}; checkDeviceSupport(callback); }; DetectRTC.MediaDevices = MediaDevices; DetectRTC.hasMicrophone = hasMicrophone; DetectRTC.hasSpeakers = hasSpeakers; DetectRTC.hasWebcam = hasWebcam; DetectRTC.isWebsiteHasWebcamPermissions = isWebsiteHasWebcamPermissions; DetectRTC.isWebsiteHasMicrophonePermissions = isWebsiteHasMicrophonePermissions; DetectRTC.audioInputDevices = audioInputDevices; DetectRTC.audioOutputDevices = audioOutputDevices; DetectRTC.videoInputDevices = videoInputDevices; // ------ var isSetSinkIdSupported = false; if ('setSinkId' in document.createElement('video')) { isSetSinkIdSupported = true; } DetectRTC.isSetSinkIdSupported = isSetSinkIdSupported; // ----- var isRTPSenderReplaceTracksSupported = false; if (DetectRTC.browser.isFirefox && typeof mozRTCPeerConnection !== 'undefined' /*&& DetectRTC.browser.version > 39*/ ) { /*global mozRTCPeerConnection:true */ if ('getSenders' in mozRTCPeerConnection.prototype) { isRTPSenderReplaceTracksSupported = true; } } else if (DetectRTC.browser.isChrome && typeof webkitRTCPeerConnection !== 'undefined') { /*global webkitRTCPeerConnection:true */ if ('getSenders' in webkitRTCPeerConnection.prototype) { isRTPSenderReplaceTracksSupported = true; } } DetectRTC.isRTPSenderReplaceTracksSupported = isRTPSenderReplaceTracksSupported; //------ var isRemoteStreamProcessingSupported = false; if (DetectRTC.browser.isFirefox && DetectRTC.browser.version > 38) { isRemoteStreamProcessingSupported = true; } DetectRTC.isRemoteStreamProcessingSupported = isRemoteStreamProcessingSupported; //------- var isApplyConstraintsSupported = false; /*global MediaStreamTrack:true */ if (typeof MediaStreamTrack !== 'undefined' && 'applyConstraints' in MediaStreamTrack.prototype) { isApplyConstraintsSupported = true; } DetectRTC.isApplyConstraintsSupported = isApplyConstraintsSupported; //------- var isMultiMonitorScreenCapturingSupported = false; if (DetectRTC.browser.isFirefox && DetectRTC.browser.version >= 43) { // version 43 merely supports platforms for multi-monitors // version 44 will support exact multi-monitor selection i.e. you can select any monitor for screen capturing. isMultiMonitorScreenCapturingSupported = true; } DetectRTC.isMultiMonitorScreenCapturingSupported = isMultiMonitorScreenCapturingSupported; DetectRTC.isPromisesSupported = !!('Promise' in window); if (typeof DetectRTC === 'undefined') { window.DetectRTC = {}; } var MediaStream = window.MediaStream; if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') { MediaStream = webkitMediaStream; } if (typeof MediaStream !== 'undefined') { DetectRTC.MediaStream = Object.keys(MediaStream.prototype); } else DetectRTC.MediaStream = false; if (typeof MediaStreamTrack !== 'undefined') { DetectRTC.MediaStreamTrack = Object.keys(MediaStreamTrack.prototype); } else DetectRTC.MediaStreamTrack = false; var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; if (typeof RTCPeerConnection !== 'undefined') { DetectRTC.RTCPeerConnection = Object.keys(RTCPeerConnection.prototype); } else DetectRTC.RTCPeerConnection = false; window.DetectRTC = DetectRTC; if (typeof module !== 'undefined' /* && !!module.exports*/ ) { module.exports = DetectRTC; } if (typeof define === 'function' && define.amd) { define('DetectRTC', [], function() { return DetectRTC; }); } })();
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ Phaser.Component = function () {}; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees. * * @class */ Phaser.Component.Angle = function () {}; Phaser.Component.Angle.prototype = { /** * The angle property is the rotation of the Game Object in *degrees* from its original orientation. * * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * * Values outside this range are added to or subtracted from 360 to obtain a value within the range. * For example, the statement player.angle = 450 is the same as player.angle = 90. * * If you wish to work in radians instead of degrees you can use the property `rotation` instead. * Working in radians is slightly faster as it doesn't have to perform any calculations. * * @property {number} angle */ angle: { get: function() { return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); }, set: function(value) { this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method. * * @class */ Phaser.Component.Animation = function () {}; Phaser.Component.Animation.prototype = { /** * Plays an Animation. * * The animation should have previously been created via `animations.add`. * * If the animation is already playing calling this again won't do anything. * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`. * * @method * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. * @return {Phaser.Animation} A reference to playing Animation. */ play: function (name, frameRate, loop, killOnComplete) { if (this.animations) { return this.animations.play(name, frameRate, loop, killOnComplete); } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera. * It is used by the InWorld component. * * @class */ Phaser.Component.AutoCull = function () {}; Phaser.Component.AutoCull.prototype = { /** * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame. * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`. * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely. * * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, * or you have tested performance and find it acceptable. * * @property {boolean} autoCull * @default */ autoCull: false, /** * Checks if the Game Objects bounds intersect with the Game Camera bounds. * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds. * * @property {boolean} inCamera * @readonly */ inCamera: { get: function() { if (!this.autoCull && !this.checkWorldBounds) { this._bounds.copyFrom(this.getBounds()); this._bounds.x += this.game.camera.view.x; this._bounds.y += this.game.camera.view.y; } return this.game.world.camera.view.intersects(this._bounds); } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Bounds component contains properties related to the bounds of the Game Object. * * @class */ Phaser.Component.Bounds = function () {}; Phaser.Component.Bounds.prototype = { /** * The amount the Game Object is visually offset from its x coordinate. * This is the same as `width * anchor.x`. * It will only be > 0 if anchor.x is not equal to zero. * * @property {number} offsetX * @readOnly */ offsetX: { get: function () { return this.anchor.x * this.width; } }, /** * The amount the Game Object is visually offset from its y coordinate. * This is the same as `height * anchor.y`. * It will only be > 0 if anchor.y is not equal to zero. * * @property {number} offsetY * @readOnly */ offsetY: { get: function () { return this.anchor.y * this.height; } }, /** * The center x coordinate of the Game Object. * This is the same as `(x - offsetX) + (width / 2)`. * * @property {number} centerX */ centerX: { get: function () { return (this.x - this.offsetX) + (this.width * 0.5); }, set: function (value) { this.x = (value + this.offsetX) - (this.width * 0.5); } }, /** * The center y coordinate of the Game Object. * This is the same as `(y - offsetY) + (height / 2)`. * * @property {number} centerY */ centerY: { get: function () { return (this.y - this.offsetY) + (this.height * 0.5); }, set: function (value) { this.y = (value + this.offsetY) - (this.height * 0.5); } }, /** * The left coordinate of the Game Object. * This is the same as `x - offsetX`. * * @property {number} left */ left: { get: function () { return this.x - this.offsetX; }, set: function (value) { this.x = value + this.offsetX; } }, /** * The right coordinate of the Game Object. * This is the same as `x + width - offsetX`. * * @property {number} right */ right: { get: function () { return (this.x + this.width) - this.offsetX; }, set: function (value) { this.x = value - (this.width) + this.offsetX; } }, /** * The y coordinate of the Game Object. * This is the same as `y - offsetY`. * * @property {number} top */ top: { get: function () { return this.y - this.offsetY; }, set: function (value) { this.y = value + this.offsetY; } }, /** * The sum of the y and height properties. * This is the same as `y + height - offsetY`. * * @property {number} bottom */ bottom: { get: function () { return (this.y + this.height) - this.offsetY; }, set: function (value) { this.y = value - (this.height) + this.offsetY; } }, /** * Aligns this Game Object within another Game Object, or Rectangle, known as the * 'container', to one of 9 possible positions. * * The container must be a Game Object, or Phaser.Rectangle object. This can include properties * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, * TileSprites or Buttons. * * Please note that aligning a Sprite to another Game Object does **not** make it a child of * the container. It simply modifies its position coordinates so it aligns with it. * * The position constants you can use are: * * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`. * * The Game Objects are placed in such a way that their _bounds_ align with the * container, taking into consideration rotation, scale and the anchor property. * This allows you to neatly align Game Objects, irrespective of their position value. * * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final * aligned position of the Game Object. For example: * * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)` * * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place. * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive * one expands it. * * @method * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. * @return {Object} This Game Object. */ alignIn: function (container, position, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } switch (position) { default: case Phaser.TOP_LEFT: this.left = container.left - offsetX; this.top = container.top - offsetY; break; case Phaser.TOP_CENTER: this.centerX = container.centerX + offsetX; this.top = container.top - offsetY; break; case Phaser.TOP_RIGHT: this.right = container.right + offsetX; this.top = container.top - offsetY; break; case Phaser.LEFT_CENTER: this.left = container.left - offsetX; this.centerY = container.centerY + offsetY; break; case Phaser.CENTER: this.centerX = container.centerX + offsetX; this.centerY = container.centerY + offsetY; break; case Phaser.RIGHT_CENTER: this.right = container.right + offsetX; this.centerY = container.centerY + offsetY; break; case Phaser.BOTTOM_LEFT: this.left = container.left - offsetX; this.bottom = container.bottom + offsetY; break; case Phaser.BOTTOM_CENTER: this.centerX = container.centerX + offsetX; this.bottom = container.bottom + offsetY; break; case Phaser.BOTTOM_RIGHT: this.right = container.right + offsetX; this.bottom = container.bottom + offsetY; break; } return this; }, /** * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the * 'parent', in one of 11 possible positions. * * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText, * TileSprites or Buttons. * * Please note that aligning a Sprite to another Game Object does **not** make it a child of * the parent. It simply modifies its position coordinates so it aligns with it. * * The position constants you can use are: * * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` * and `Phaser.BOTTOM_RIGHT`. * * The Game Objects are placed in such a way that their _bounds_ align with the * parent, taking into consideration rotation, scale and the anchor property. * This allows you to neatly align Game Objects, irrespective of their position value. * * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final * aligned position of the Game Object. For example: * * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)` * * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner. * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place. * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive * one expands it. * * @method * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`. * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it. * @return {Object} This Game Object. */ alignTo: function (parent, position, offsetX, offsetY) { if (offsetX === undefined) { offsetX = 0; } if (offsetY === undefined) { offsetY = 0; } switch (position) { default: case Phaser.TOP_LEFT: this.left = parent.left - offsetX; this.bottom = parent.top - offsetY; break; case Phaser.TOP_CENTER: this.centerX = parent.centerX + offsetX; this.bottom = parent.top - offsetY; break; case Phaser.TOP_RIGHT: this.right = parent.right + offsetX; this.bottom = parent.top - offsetY; break; case Phaser.LEFT_TOP: this.right = parent.left - offsetX; this.top = parent.top - offsetY; break; case Phaser.LEFT_CENTER: this.right = parent.left - offsetX; this.centerY = parent.centerY + offsetY; break; case Phaser.LEFT_BOTTOM: this.right = parent.left - offsetX; this.bottom = parent.bottom + offsetY; break; case Phaser.RIGHT_TOP: this.left = parent.right + offsetX; this.top = parent.top - offsetY; break; case Phaser.RIGHT_CENTER: this.left = parent.right + offsetX; this.centerY = parent.centerY + offsetY; break; case Phaser.RIGHT_BOTTOM: this.left = parent.right + offsetX; this.bottom = parent.bottom + offsetY; break; case Phaser.BOTTOM_LEFT: this.left = parent.left - offsetX; this.top = parent.bottom + offsetY; break; case Phaser.BOTTOM_CENTER: this.centerX = parent.centerX + offsetX; this.top = parent.bottom + offsetY; break; case Phaser.BOTTOM_RIGHT: this.right = parent.right + offsetX; this.top = parent.bottom + offsetY; break; } return this; } }; // Phaser.Group extensions Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn; Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The BringToTop Component features quick access to Group sorting related methods. * * @class */ Phaser.Component.BringToTop = function () {}; /** * Brings this Game Object to the top of its parents display list. * Visually this means it will render over the top of any old child in the same Group. * * If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World, * because the World is the root Group from which all Game Objects descend. * * @method * @return {PIXI.DisplayObject} This instance. */ Phaser.Component.BringToTop.prototype.bringToTop = function() { if (this.parent) { this.parent.bringToTop(this); } return this; }; /** * Sends this Game Object to the bottom of its parents display list. * Visually this means it will render below all other children in the same Group. * * If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World, * because the World is the root Group from which all Game Objects descend. * * @method * @return {PIXI.DisplayObject} This instance. */ Phaser.Component.BringToTop.prototype.sendToBack = function() { if (this.parent) { this.parent.sendToBack(this); } return this; }; /** * Moves this Game Object up one place in its parents display list. * This call has no effect if the Game Object is already at the top of the display list. * * If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World, * because the World is the root Group from which all Game Objects descend. * * @method * @return {PIXI.DisplayObject} This instance. */ Phaser.Component.BringToTop.prototype.moveUp = function () { if (this.parent) { this.parent.moveUp(this); } return this; }; /** * Moves this Game Object down one place in its parents display list. * This call has no effect if the Game Object is already at the bottom of the display list. * * If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World, * because the World is the root Group from which all Game Objects descend. * * @method * @return {PIXI.DisplayObject} This instance. */ Phaser.Component.BringToTop.prototype.moveDown = function () { if (this.parent) { this.parent.moveDown(this); } return this; }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Core Component Features. * * @class */ Phaser.Component.Core = function () {}; /** * Installs / registers mixin components. * * The `this` context should be that of the applicable object instance or prototype. * * @method * @protected */ Phaser.Component.Core.install = function (components) { // Always install 'Core' first Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype); this.components = {}; for (var i = 0; i < components.length; i++) { var id = components[i]; var replace = false; if (id === 'Destroy') { replace = true; } Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace); this.components[id] = true; } }; /** * Initializes the mixin components. * * The `this` context should be an instance of the component mixin target. * * @method * @protected */ Phaser.Component.Core.init = function (game, x, y, key, frame) { this.game = game; this.key = key; this.data = {}; this.position.set(x, y); this.world = new Phaser.Point(x, y); this.previousPosition = new Phaser.Point(x, y); this.events = new Phaser.Events(this); this._bounds = new Phaser.Rectangle(); if (this.components.PhysicsBody) { // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype. this.body = this.body; } if (this.components.Animation) { this.animations = new Phaser.AnimationManager(this); } if (this.components.LoadTexture && key !== null) { this.loadTexture(key, frame); } if (this.components.FixedToCamera) { this.cameraOffset = new Phaser.Point(x, y); } }; Phaser.Component.Core.preUpdate = function () { if (this.pendingDestroy) { this.destroy(); return; } this.previousPosition.set(this.world.x, this.world.y); this.previousRotation = this.rotation; if (!this.exists || !this.parent.exists) { this.renderOrderID = -1; return false; } this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty); if (this.visible) { this.renderOrderID = this.game.stage.currentRenderOrderID++; } if (this.animations) { this.animations.update(); } if (this.body) { this.body.preUpdate(); } for (var i = 0; i < this.children.length; i++) { this.children[i].preUpdate(); } return true; }; Phaser.Component.Core.prototype = { /** * A reference to the currently running Game. * @property {Phaser.Game} game */ game: null, /** * A user defined name given to this Game Object. * This value isn't ever used internally by Phaser, it is meant as a game level property. * @property {string} name * @default */ name: '', /** * An empty Object that belongs to this Game Object. * This value isn't ever used internally by Phaser, but may be used by your own code, or * by Phaser Plugins, to store data that needs to be associated with the Game Object, * without polluting the Game Object directly. * @property {Object} data * @default */ data: {}, /** * The components this Game Object has installed. * @property {object} components * @protected */ components: {}, /** * The z depth of this Game Object within its parent Group. * No two objects in a Group can have the same z value. * This value is adjusted automatically whenever the Group hierarchy changes. * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop. * @property {number} z * @readOnly */ z: 0, /** * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this * Game Object, or any of its components. * @see Phaser.Events * @property {Phaser.Events} events */ events: undefined, /** * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance. * Through it you can create, play, pause and stop animations. * @see Phaser.AnimationManager * @property {Phaser.AnimationManager} animations */ animations: undefined, /** * The key of the image or texture used by this Game Object during rendering. * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache. * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache. * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it. * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key */ key: '', /** * The world coordinates of this Game Object in pixels. * Depending on where in the display list this Game Object is placed this value can differ from `position`, * which contains the x/y coordinates relative to the Game Objects parent. * @property {Phaser.Point} world */ world: null, /** * A debug flag designed for use with `Game.enableStep`. * @property {boolean} debug * @default */ debug: false, /** * The position the Game Object was located in the previous frame. * @property {Phaser.Point} previousPosition * @readOnly */ previousPosition: null, /** * The rotation the Game Object was in set to in the previous frame. Value is in radians. * @property {number} previousRotation * @readOnly */ previousRotation: 0, /** * The render order ID is used internally by the renderer and Input Manager and should not be modified. * This property is mostly used internally by the renderers, but is exposed for the use of plugins. * @property {number} renderOrderID * @readOnly */ renderOrderID: 0, /** * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update. * This property is mostly used internally by the physics systems, but is exposed for the use of plugins. * @property {boolean} fresh * @readOnly */ fresh: true, /** * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update. * You can set it directly to allow you to flag an object to be destroyed on its next update. * * This is extremely useful if you wish to destroy an object from within one of its own callbacks * such as with Buttons or other Input events. * * @property {boolean} pendingDestroy */ pendingDestroy: false, /** * @property {Phaser.Rectangle} _bounds - Internal cache var. * @private */ _bounds: null, /** * @property {boolean} _exists - Internal cache var. * @private */ _exists: true, /** * Controls if this Game Object is processed by the core game loop. * If this Game Object has a physics body it also controls if its physics body is updated or not. * When `exists` is set to `false` it will remove its physics body from the physics world if it has one. * It also toggles the `visible` property to false as well. * * Setting `exists` to true will add its physics body back in to the physics world, if it has one. * It will also set the `visible` property to `true`. * * @property {boolean} exists */ exists: { get: function () { return this._exists; }, set: function (value) { if (value) { this._exists = true; if (this.body && this.body.type === Phaser.Physics.P2JS) { this.body.addToWorld(); } this.visible = true; } else { this._exists = false; if (this.body && this.body.type === Phaser.Physics.P2JS) { this.body.removeFromWorld(); } this.visible = false; } } }, /** * Override this method in your own custom objects to handle any update requirements. * It is called immediately after `preUpdate` and before `postUpdate`. * Remember if this Game Object has any children you should call update on those too. * * @method */ update: function() { }, /** * Internal method called by the World postUpdate cycle. * * @method * @protected */ postUpdate: function() { if (this.customRender) { this.key.render(); } if (this.components.PhysicsBody) { Phaser.Component.PhysicsBody.postUpdate.call(this); } if (this.components.FixedToCamera) { Phaser.Component.FixedToCamera.postUpdate.call(this); } for (var i = 0; i < this.children.length; i++) { this.children[i].postUpdate(); } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Crop component provides the ability to crop a texture based Game Object to a defined rectangle, * which can be updated in real-time. * * @class */ Phaser.Component.Crop = function () {}; Phaser.Component.Crop.prototype = { /** * The Rectangle used to crop the texture this Game Object uses. * Set this property via `crop`. * If you modify this property directly you must call `updateCrop` in order to have the change take effect. * @property {Phaser.Rectangle} cropRect * @default */ cropRect: null, /** * @property {Phaser.Rectangle} _crop - Internal cache var. * @private */ _crop: null, /** * Crop allows you to crop the texture being used to display this Game Object. * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly. * * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method, * or by modifying `cropRect` property directly and then calling `updateCrop`. * * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties. * * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`, * in which case the values are duplicated to a local object. * * @method * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle. * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect. */ crop: function (rect, copy) { if (copy === undefined) { copy = false; } if (rect) { if (copy && this.cropRect !== null) { this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height); } else if (copy && this.cropRect === null) { this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height); } else { this.cropRect = rect; } this.updateCrop(); } else { this._crop = null; this.cropRect = null; this.resetFrame(); } }, /** * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property, * or the rectangle it references, then you need to update the crop frame by calling this method. * * @method */ updateCrop: function () { if (!this.cropRect) { return; } var oldX = this.texture.crop.x; var oldY = this.texture.crop.y; var oldW = this.texture.crop.width; var oldH = this.texture.crop.height; this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop); this._crop.x += this._frame.x; this._crop.y += this._frame.y; var cx = Math.max(this._frame.x, this._crop.x); var cy = Math.max(this._frame.y, this._crop.y); var cw = Math.min(this._frame.right, this._crop.right) - cx; var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy; this.texture.crop.x = cx; this.texture.crop.y = cy; this.texture.crop.width = cw; this.texture.crop.height = ch; this.texture.frame.width = Math.min(cw, this.cropRect.width); this.texture.frame.height = Math.min(ch, this.cropRect.height); this.texture.width = this.texture.frame.width; this.texture.height = this.texture.frame.height; this.texture._updateUvs(); if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch)) { this.texture.requiresReTint = true; } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Delta component provides access to delta values between the Game Objects current and previous position. * * @class */ Phaser.Component.Delta = function () {}; Phaser.Component.Delta.prototype = { /** * Returns the delta x value. The difference between world.x now and in the previous frame. * * The value will be positive if the Game Object has moved to the right or negative if to the left. * * @property {number} deltaX * @readonly */ deltaX: { get: function() { return this.world.x - this.previousPosition.x; } }, /** * Returns the delta y value. The difference between world.y now and in the previous frame. * * The value will be positive if the Game Object has moved down or negative if up. * * @property {number} deltaY * @readonly */ deltaY: { get: function() { return this.world.y - this.previousPosition.y; } }, /** * Returns the delta z value. The difference between rotation now and in the previous frame. * * @property {number} deltaZ - The delta value. * @readonly */ deltaZ: { get: function() { return this.rotation - this.previousRotation; } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Destroy component is responsible for destroying a Game Object. * * @class */ Phaser.Component.Destroy = function () {}; Phaser.Component.Destroy.prototype = { /** * As a Game Object runs through its destroy method this flag is set to true, * and can be checked in any sub-systems or plugins it is being destroyed from. * @property {boolean} destroyPhase * @readOnly */ destroyPhase: false, /** * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present * and nulls its reference to `game`, freeing it up for garbage collection. * * If this Game Object has the Events component it will also dispatch the `onDestroy` event. * * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've * more than one Game Object sharing the same BaseTexture. * * @method * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well? * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it. */ destroy: function (destroyChildren, destroyTexture) { if (this.game === null || this.destroyPhase) { return; } if (destroyChildren === undefined) { destroyChildren = true; } if (destroyTexture === undefined) { destroyTexture = false; } this.destroyPhase = true; if (this.events) { this.events.onDestroy$dispatch(this); } if (this.parent) { if (this.parent instanceof Phaser.Group) { this.parent.remove(this); } else { this.parent.removeChild(this); } } if (this.input) { this.input.destroy(); } if (this.animations) { this.animations.destroy(); } if (this.body) { this.body.destroy(); } if (this.events) { this.events.destroy(); } this.game.tweens.removeFrom(this); var i = this.children.length; if (destroyChildren) { while (i--) { this.children[i].destroy(destroyChildren); } } else { while (i--) { this.removeChild(this.children[i]); } } if (this._crop) { this._crop = null; this.cropRect = null; } if (this._frame) { this._frame = null; } if (Phaser.Video && this.key instanceof Phaser.Video) { this.key.onChangeSource.remove(this.resizeFrame, this); } if (Phaser.BitmapText && this._glyphs) { this._glyphs = []; } this.alive = false; this.exists = false; this.visible = false; this.filters = null; this.mask = null; this.game = null; this.data = {}; // In case Pixi is still going to try and render it even though destroyed this.renderable = false; if (this.transformCallback) { this.transformCallback = null; this.transformCallbackContext = null; } // Pixi level DisplayObject destroy this.hitArea = null; this.parent = null; this.stage = null; this.worldTransform = null; this.filterArea = null; this._bounds = null; this._currentBounds = null; this._mask = null; this._destroyCachedSprite(); // Texture? if (destroyTexture) { this.texture.destroy(true); } this.destroyPhase = false; this.pendingDestroy = false; } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Events component is a collection of events fired by the parent Game Object. * * Phaser uses what are known as 'Signals' for all event handling. All of the events in * this class are signals you can subscribe to, much in the same way you'd "listen" for * an event. * * For example to tell when a Sprite has been added to a new group, you can bind a function * to the `onAddedToGroup` signal: * * `sprite.events.onAddedToGroup.add(yourFunction, this);` * * Where `yourFunction` is the function you want called when this event occurs. * * For more details about how signals work please see the Phaser.Signal class. * * The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true` * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}. * * @class Phaser.Events * @constructor * @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object. */ Phaser.Events = function (sprite) { /** * @property {Phaser.Sprite} parent - The Sprite that owns these events. */ this.parent = sprite; // The signals are automatically added by the corresponding proxy properties }; Phaser.Events.prototype = { /** * Removes all events. * * @method Phaser.Events#destroy */ destroy: function () { this._parent = null; if (this._onDestroy) { this._onDestroy.dispose(); } if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); } if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); } if (this._onRemovedFromWorld) { this._onRemovedFromWorld.dispose(); } if (this._onKilled) { this._onKilled.dispose(); } if (this._onRevived) { this._onRevived.dispose(); } if (this._onEnterBounds) { this._onEnterBounds.dispose(); } if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); } if (this._onInputOver) { this._onInputOver.dispose(); } if (this._onInputOut) { this._onInputOut.dispose(); } if (this._onInputDown) { this._onInputDown.dispose(); } if (this._onInputUp) { this._onInputUp.dispose(); } if (this._onDragStart) { this._onDragStart.dispose(); } if (this._onDragUpdate) { this._onDragUpdate.dispose(); } if (this._onDragStop) { this._onDragStop.dispose(); } if (this._onAnimationStart) { this._onAnimationStart.dispose(); } if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); } if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); } }, // The following properties are sentinels that will be replaced with getters /** * This signal is dispatched when this Game Object is added to a new Group. * It is sent two arguments: * {any} The Game Object that was added to the Group. * {Phaser.Group} The Group it was added to. * @property {Phaser.Signal} onAddedToGroup */ onAddedToGroup: null, /** * This signal is dispatched when the Game Object is removed from a Group. * It is sent two arguments: * {any} The Game Object that was removed from the Group. * {Phaser.Group} The Group it was removed from. * @property {Phaser.Signal} onRemovedFromGroup */ onRemovedFromGroup: null, /** * This Signal is never used internally by Phaser and is now deprecated. * @deprecated * @property {Phaser.Signal} onRemovedFromWorld */ onRemovedFromWorld: null, /** * This signal is dispatched when the Game Object is destroyed. * This happens when `Sprite.destroy()` is called, or `Group.destroy()` with `destroyChildren` set to true. * It is sent one argument: * {any} The Game Object that was destroyed. * @property {Phaser.Signal} onDestroy */ onDestroy: null, /** * This signal is dispatched when the Game Object is killed. * This happens when `Sprite.kill()` is called. * Please understand the difference between `kill` and `destroy` by looking at their respective methods. * It is sent one argument: * {any} The Game Object that was killed. * @property {Phaser.Signal} onKilled */ onKilled: null, /** * This signal is dispatched when the Game Object is revived from a previously killed state. * This happens when `Sprite.revive()` is called. * It is sent one argument: * {any} The Game Object that was revived. * @property {Phaser.Signal} onRevived */ onRevived: null, /** * This signal is dispatched when the Game Object leaves the Phaser.World bounds. * This signal is only if `Sprite.checkWorldBounds` is set to `true`. * It is sent one argument: * {any} The Game Object that left the World bounds. * @property {Phaser.Signal} onOutOfBounds */ onOutOfBounds: null, /** * This signal is dispatched when the Game Object returns within the Phaser.World bounds, having previously been outside of them. * This signal is only if `Sprite.checkWorldBounds` is set to `true`. * It is sent one argument: * {any} The Game Object that entered the World bounds. * @property {Phaser.Signal} onEnterBounds */ onEnterBounds: null, /** * This signal is dispatched if the Game Object has `inputEnabled` set to `true`, * and receives an over event from a Phaser.Pointer. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * @property {Phaser.Signal} onInputOver */ onInputOver: null, /** * This signal is dispatched if the Game Object has `inputEnabled` set to `true`, * and receives an out event from a Phaser.Pointer, which was previously over it. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * @property {Phaser.Signal} onInputOut */ onInputOut: null, /** * This signal is dispatched if the Game Object has `inputEnabled` set to `true`, * and receives a down event from a Phaser.Pointer. This effectively means the Pointer has been * pressed down (but not yet released) on the Game Object. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * @property {Phaser.Signal} onInputDown */ onInputDown: null, /** * This signal is dispatched if the Game Object has `inputEnabled` set to `true`, * and receives an up event from a Phaser.Pointer. This effectively means the Pointer had been * pressed down, and was then released on the Game Object. * It is sent three arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * {boolean} isOver - Is the Pointer still over the Game Object? * @property {Phaser.Signal} onInputUp */ onInputUp: null, /** * This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set. * It is sent when a Phaser.Pointer starts to drag the Game Object, taking into consideration the various * drag limitations that may be set. * It is sent four arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * {number} The x coordinate that the drag started from. * {number} The y coordinate that the drag started from. * @property {Phaser.Signal} onDragStart */ onDragStart: null, /** * This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set. * It is sent when a Phaser.Pointer is actively dragging the Game Object. * Be warned: This is a high volume Signal. Be careful what you bind to it. * It is sent six arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * {number} The new x coordinate of the Game Object. * {number} The new y coordinate of the Game Object. * {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled. * {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started. * @property {Phaser.Signal} onDragUpdate */ onDragUpdate: null, /** * This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set. * It is sent when a Phaser.Pointer stops dragging the Game Object. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Pointer} The Phaser.Pointer object that caused the event. * @property {Phaser.Signal} onDragStop */ onDragStop: null, /** * This signal is dispatched if the Game Object has the AnimationManager component, * and an Animation has been played. * You can also listen to `Animation.onStart` rather than via the Game Objects events. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Animation} The Phaser.Animation that was started. * @property {Phaser.Signal} onAnimationStart */ onAnimationStart: null, /** * This signal is dispatched if the Game Object has the AnimationManager component, * and an Animation has been stopped (via `animation.stop()` and the `dispatchComplete` argument has been set. * You can also listen to `Animation.onComplete` rather than via the Game Objects events. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Animation} The Phaser.Animation that was stopped. * @property {Phaser.Signal} onAnimationComplete */ onAnimationComplete: null, /** * This signal is dispatched if the Game Object has the AnimationManager component, * and an Animation has looped playback. * You can also listen to `Animation.onLoop` rather than via the Game Objects events. * It is sent two arguments: * {any} The Game Object that received the event. * {Phaser.Animation} The Phaser.Animation that looped. * @property {Phaser.Signal} onAnimationLoop */ onAnimationLoop: null }; Phaser.Events.prototype.constructor = Phaser.Events; // Create an auto-create proxy getter and dispatch method for all events. // The backing property is the same as the event name, prefixed with '_' // and the dispatch method is the same as the event name postfixed with '$dispatch'. for (var prop in Phaser.Events.prototype) { if (!Phaser.Events.prototype.hasOwnProperty(prop) || prop.indexOf('on') !== 0 || Phaser.Events.prototype[prop] !== null) { continue; } (function (prop, backing) { 'use strict'; // The accessor creates a new Signal; and so it should only be used from user-code. Object.defineProperty(Phaser.Events.prototype, prop, { get: function () { return this[backing] || (this[backing] = new Phaser.Signal()); } }); // The dispatcher will only broadcast on an already-created signal; call this internally. Phaser.Events.prototype[prop + '$dispatch'] = function () { return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null; }; })(prop, '_' + prop); } /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless * of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world. * * @class */ Phaser.Component.FixedToCamera = function () {}; /** * The FixedToCamera component postUpdate handler. * Called automatically by the Game Object. * * @method */ Phaser.Component.FixedToCamera.postUpdate = function () { if (this.fixedToCamera) { this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x; this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y; } }; Phaser.Component.FixedToCamera.prototype = { /** * @property {boolean} _fixedToCamera * @private */ _fixedToCamera: false, /** * A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering. * * The values are adjusted at the rendering stage, overriding the Game Objects actual world position. * * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times * regardless where in the world the camera is. * * The offsets are stored in the `cameraOffset` property. * * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list. * * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them. * * @property {boolean} fixedToCamera */ fixedToCamera: { get: function () { return this._fixedToCamera; }, set: function (value) { if (value) { this._fixedToCamera = true; this.cameraOffset.set(this.x, this.y); } else { this._fixedToCamera = false; } } }, /** * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true. * * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list. * @property {Phaser.Point} cameraOffset */ cameraOffset: new Phaser.Point() }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Health component provides the ability for Game Objects to have a `health` property * that can be damaged and reset through game code. * Requires the LifeSpan component. * * @class */ Phaser.Component.Health = function () {}; Phaser.Component.Health.prototype = { /** * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object. * * It can be used in combination with the `damage` method or modified directly. * * @property {number} health * @default */ health: 1, /** * The Game Objects maximum health value. This works in combination with the `heal` method to ensure * the health value never exceeds the maximum. * * @property {number} maxHealth * @default */ maxHealth: 100, /** * Damages the Game Object. This removes the given amount of health from the `health` property. * * If health is taken below or is equal to zero then the `kill` method is called. * * @member * @param {number} amount - The amount to subtract from the current `health` value. * @return {Phaser.Sprite} This instance. */ damage: function (amount) { if (this.alive) { this.health -= amount; if (this.health <= 0) { this.kill(); } } return this; }, /** * Sets the health property of the Game Object to the given amount. * Will never exceed the `maxHealth` value. * * @member * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`. * @return {Phaser.Sprite} This instance. */ setHealth: function (amount) { this.health = amount; if (this.health > this.maxHealth) { this.health = this.maxHealth; } return this; }, /** * Heal the Game Object. This adds the given amount of health to the `health` property. * * @member * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`. * @return {Phaser.Sprite} This instance. */ heal: function (amount) { if (this.alive) { this.health += amount; if (this.health > this.maxHealth) { this.health = this.maxHealth; } } return this; } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The InCamera component checks if the Game Object intersects with the Game Camera. * * @class */ Phaser.Component.InCamera = function () {}; Phaser.Component.InCamera.prototype = { /** * Checks if this Game Objects bounds intersects with the Game Cameras bounds. * * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds. * * An object outside the bounds can be considered for camera culling if it has the AutoCull component. * * @property {boolean} inCamera * @readonly */ inCamera: { get: function() { return this.game.world.camera.view.intersects(this._bounds); } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The InputEnabled component allows a Game Object to have its own InputHandler and process input related events. * * @class */ Phaser.Component.InputEnabled = function () {}; Phaser.Component.InputEnabled.prototype = { /** * The Input Handler for this Game Object. * * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`. * * After you have done this, this property will be a reference to the Phaser InputHandler. * @property {Phaser.InputHandler|null} input */ input: null, /** * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created * for this Game Object and it will then start to process click / touch events and more. * * You can then access the Input Handler via `this.input`. * * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`. * * If you set this property to false it will stop the Input Handler from processing any more input events. * * If you want to _temporarily_ disable input for a Game Object, then it's better to set * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties. * You can then toggle this back on as needed. * * @property {boolean} inputEnabled */ inputEnabled: { get: function () { return (this.input && this.input.enabled); }, set: function (value) { if (value) { if (this.input === null) { this.input = new Phaser.InputHandler(this); this.input.start(); } else if (this.input && !this.input.enabled) { this.input.start(); } } else { if (this.input && this.input.enabled) { this.input.stop(); } } } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The InWorld component checks if a Game Object is within the Game World Bounds. * An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds. * If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well. * * @class */ Phaser.Component.InWorld = function () {}; /** * The InWorld component preUpdate handler. * Called automatically by the Game Object. * * @method */ Phaser.Component.InWorld.preUpdate = function () { // Cache the bounds if we need it if (this.autoCull || this.checkWorldBounds) { this._bounds.copyFrom(this.getBounds()); this._bounds.x += this.game.camera.view.x; this._bounds.y += this.game.camera.view.y; if (this.autoCull) { // Won't get rendered but will still get its transform updated if (this.game.world.camera.view.intersects(this._bounds)) { this.renderable = true; this.game.world.camera.totalInView++; } else { this.renderable = false; if (this.outOfCameraBoundsKill) { this.kill(); return false; } } } if (this.checkWorldBounds) { // The Sprite is already out of the world bounds, so let's check to see if it has come back again if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds)) { this._outOfBoundsFired = false; this.events.onEnterBounds$dispatch(this); } else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds)) { // The Sprite WAS in the screen, but has now left. this._outOfBoundsFired = true; this.events.onOutOfBounds$dispatch(this); if (this.outOfBoundsKill) { this.kill(); return false; } } } } return true; }; Phaser.Component.InWorld.prototype = { /** * If this is set to `true` the Game Object checks if it is within the World bounds each frame. * * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event. * * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event. * * It also optionally kills the Game Object if `outOfBoundsKill` is `true`. * * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame. * * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required, * or you have tested performance and find it acceptable. * * @property {boolean} checkWorldBounds * @default */ checkWorldBounds: false, /** * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false. * * @property {boolean} outOfBoundsKill * @default */ outOfBoundsKill: false, /** * If this and the `autoCull` property are both set to `true`, then the `kill` method * is called as soon as the Game Object leaves the camera bounds. * * @property {boolean} outOfCameraBoundsKill * @default */ outOfCameraBoundsKill: false, /** * @property {boolean} _outOfBoundsFired - Internal state var. * @private */ _outOfBoundsFired: false, /** * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds. * * @property {boolean} inWorld * @readonly */ inWorld: { get: function () { return this.game.world.bounds.intersects(this.getBounds()); } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * LifeSpan Component Features. * * @class */ Phaser.Component.LifeSpan = function () {}; /** * The LifeSpan component preUpdate handler. * Called automatically by the Game Object. * * @method */ Phaser.Component.LifeSpan.preUpdate = function () { if (this.lifespan > 0) { this.lifespan -= this.game.time.physicsElapsedMS; if (this.lifespan <= 0) { this.kill(); return false; } } return true; }; Phaser.Component.LifeSpan.prototype = { /** * A useful flag to control if the Game Object is alive or dead. * * This is set automatically by the Health components `damage` method should the object run out of health. * Or you can toggle it via your game code. * * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates. * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling. * @property {boolean} alive * @default */ alive: true, /** * The lifespan allows you to give a Game Object a lifespan in milliseconds. * * Once the Game Object is 'born' you can set this to a positive value. * * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame. * When it reaches zero it will call the `kill` method. * * Very handy for particles, bullets, collectibles, or any other short-lived entity. * * @property {number} lifespan * @default */ lifespan: 0, /** * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process. * * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true. * * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal. * * @method * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component. * @return {PIXI.DisplayObject} This instance. */ revive: function (health) { if (health === undefined) { health = 100; } this.alive = true; this.exists = true; this.visible = true; if (typeof this.setHealth === 'function') { this.setHealth(health); } if (this.events) { this.events.onRevived$dispatch(this); } return this; }, /** * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false. * * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal. * * Note that killing a Game Object is a way for you to quickly recycle it in an object pool, * it doesn't destroy the object or free it up from memory. * * If you don't need this Game Object any more you should call `destroy` instead. * * @method * @return {PIXI.DisplayObject} This instance. */ kill: function () { this.alive = false; this.exists = false; this.visible = false; if (this.events) { this.events.onKilled$dispatch(this); } return this; } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames. * * @class */ Phaser.Component.LoadTexture = function () {}; Phaser.Component.LoadTexture.prototype = { /** * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc) * @private */ customRender: false, /** * @property {Phaser.Rectangle} _frame - Internal cache var. * @private */ _frame: null, /** * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache. * * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead. * * You should only use `loadTexture` if you want to replace the base texture entirely. * * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU. * * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite. * Doing this then sets the key to be the `frame` argument (the frame is set to zero). * * This allows you to create sprites using `load.image` during development, and then change them * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS' * and swapping it to be the key of the atlas data. * * Note: You cannot use a RenderTexture as a texture for a TileSprite. * * @method * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing. */ loadTexture: function (key, frame, stopAnimation) { if (key === Phaser.PENDING_ATLAS) { key = frame; frame = 0; } else { frame = frame || 0; } if ((stopAnimation || stopAnimation === undefined) && this.animations) { this.animations.stop(); } this.key = key; this.customRender = false; var cache = this.game.cache; var setFrame = true; var smoothed = !this.texture.baseTexture.scaleMode; if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture) { this.key = key.key; this.setTexture(key); } else if (Phaser.BitmapData && key instanceof Phaser.BitmapData) { this.customRender = true; this.setTexture(key.texture); if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA)) { setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame); } else { setFrame = !this.animations.loadFrameData(key.frameData, 0); } } else if (Phaser.Video && key instanceof Phaser.Video) { this.customRender = true; // This works from a reference, which probably isn't what we need here var valid = key.texture.valid; this.setTexture(key.texture); this.setFrame(key.texture.frame.clone()); key.onChangeSource.add(this.resizeFrame, this); this.texture.valid = valid; } else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer) { // this.customRender = true; this.setTexture(PIXI.Texture.fromCanvas(key.canvas)); } else if (key instanceof PIXI.Texture) { this.setTexture(key); } else { var img = cache.getImage(key, true); this.key = img.key; this.setTexture(new PIXI.Texture(img.base)); if (key === '__default') { this.texture.baseTexture.skipRender = true; } else { this.texture.baseTexture.skipRender = false; } setFrame = !this.animations.loadFrameData(img.frameData, frame); } if (setFrame) { this._frame = Phaser.Rectangle.clone(this.texture.frame); } if (!smoothed) { this.texture.baseTexture.scaleMode = 1; } }, /** * Sets the texture frame the Game Object uses for rendering. * * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes. * * @method * @param {Phaser.Frame} frame - The Frame to be used by the texture. */ setFrame: function (frame) { this._frame = frame; this.texture.frame.x = frame.x; this.texture.frame.y = frame.y; this.texture.frame.width = frame.width; this.texture.frame.height = frame.height; this.texture.crop.x = frame.x; this.texture.crop.y = frame.y; this.texture.crop.width = frame.width; this.texture.crop.height = frame.height; if (frame.trimmed) { if (this.texture.trim) { this.texture.trim.x = frame.spriteSourceSizeX; this.texture.trim.y = frame.spriteSourceSizeY; this.texture.trim.width = frame.sourceSizeW; this.texture.trim.height = frame.sourceSizeH; } else { this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH }; } this.texture.width = frame.sourceSizeW; this.texture.height = frame.sourceSizeH; this.texture.frame.width = frame.sourceSizeW; this.texture.frame.height = frame.sourceSizeH; } else if (!frame.trimmed && this.texture.trim) { this.texture.trim = null; } if (this.cropRect) { this.updateCrop(); } this.texture.requiresReTint = true; this.texture._updateUvs(); if (this.tilingTexture) { this.refreshTexture = true; } }, /** * Resizes the Frame dimensions that the Game Object uses for rendering. * * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData * it can be useful to adjust the dimensions directly in this way. * * @method * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object. * @param {integer} width - The new width of the texture. * @param {integer} height - The new height of the texture. */ resizeFrame: function (parent, width, height) { this.texture.frame.resize(width, height); this.texture.setFrame(this.texture.frame); }, /** * Resets the texture frame dimensions that the Game Object uses for rendering. * * @method */ resetFrame: function () { if (this._frame) { this.setFrame(this._frame); } }, /** * Gets or sets the current frame index of the texture being used to render this Game Object. * * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use, * for example: `player.frame = 4`. * * If the frame index given doesn't exist it will revert to the first frame found in the texture. * * If you are using a texture atlas then you should use the `frameName` property instead. * * If you wish to fully replace the texture being used see `loadTexture`. * @property {integer} frame */ frame: { get: function () { return this.animations.frame; }, set: function (value) { this.animations.frame = value; } }, /** * Gets or sets the current frame name of the texture being used to render this Game Object. * * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use, * for example: `player.frameName = "idle"`. * * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning. * * If you are using a sprite sheet then you should use the `frame` property instead. * * If you wish to fully replace the texture being used see `loadTexture`. * @property {string} frameName */ frameName: { get: function () { return this.animations.frameName; }, set: function (value) { this.animations.frameName = value; } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object. * * @class */ Phaser.Component.Overlap = function () {}; Phaser.Component.Overlap.prototype = { /** * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object, * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result. * * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result. * * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency. * It should be fine for low-volume testing where physics isn't required. * * @method * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against. * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object. */ overlap: function (displayObject) { return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds()); } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The PhysicsBody component manages the Game Objects physics body and physics enabling. * It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself. * * @class */ Phaser.Component.PhysicsBody = function () {}; /** * The PhysicsBody component preUpdate handler. * Called automatically by the Game Object. * * @method */ Phaser.Component.PhysicsBody.preUpdate = function () { if (this.fresh && this.exists) { this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y); this.worldTransform.tx = this.world.x; this.worldTransform.ty = this.world.y; this.previousPosition.set(this.world.x, this.world.y); this.previousRotation = this.rotation; if (this.body) { this.body.preUpdate(); } this.fresh = false; return false; } this.previousPosition.set(this.world.x, this.world.y); this.previousRotation = this.rotation; if (!this._exists || !this.parent.exists) { this.renderOrderID = -1; return false; } return true; }; /** * The PhysicsBody component postUpdate handler. * Called automatically by the Game Object. * * @method */ Phaser.Component.PhysicsBody.postUpdate = function () { if (this.exists && this.body) { this.body.postUpdate(); } }; Phaser.Component.PhysicsBody.prototype = { /** * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated * properties and methods via it. * * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`. * * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`. * * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group. * * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5, * so the physics body is centered on the Game Object. * * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics. * * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body * @default */ body: null, /** * The position of the Game Object on the x axis relative to the local coordinates of the parent. * * @property {number} x */ x: { get: function () { return this.position.x; }, set: function (value) { this.position.x = value; if (this.body && !this.body.dirty) { this.body._reset = true; } } }, /** * The position of the Game Object on the y axis relative to the local coordinates of the parent. * * @property {number} y */ y: { get: function () { return this.position.y; }, set: function (value) { this.position.y = value; if (this.body && !this.body.dirty) { this.body._reset = true; } } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Reset component allows a Game Object to be reset and repositioned to a new location. * * @class */ Phaser.Component.Reset = function () {}; /** * Resets the Game Object. * * This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`, * `visible` and `renderable` to true. * * If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value. * * If this Game Object has a Physics Body it will reset the Body. * * @method * @param {number} x - The x coordinate (in world space) to position the Game Object at. * @param {number} y - The y coordinate (in world space) to position the Game Object at. * @param {number} [health=1] - The health to give the Game Object if it has the Health component. * @return {PIXI.DisplayObject} This instance. */ Phaser.Component.Reset.prototype.reset = function (x, y, health) { if (health === undefined) { health = 1; } this.world.set(x, y); this.position.set(x, y); this.fresh = true; this.exists = true; this.visible = true; this.renderable = true; if (this.components.InWorld) { this._outOfBoundsFired = false; } if (this.components.LifeSpan) { this.alive = true; this.health = health; } if (this.components.PhysicsBody) { if (this.body) { this.body.reset(x, y, false, false); } } return this; }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent. * * @class */ Phaser.Component.ScaleMinMax = function () {}; Phaser.Component.ScaleMinMax.prototype = { /** * The callback that will apply any scale limiting to the worldTransform. * @property {function} transformCallback */ transformCallback: null, /** * The context under which `transformCallback` is called. * @property {object} transformCallbackContext */ transformCallbackContext: this, /** * The minimum scale this Game Object will scale down to. * * It allows you to prevent a parent from scaling this Game Object lower than the given value. * * Set it to `null` to remove the limit. * @property {Phaser.Point} scaleMin */ scaleMin: null, /** * The maximum scale this Game Object will scale up to. * * It allows you to prevent a parent from scaling this Game Object higher than the given value. * * Set it to `null` to remove the limit. * @property {Phaser.Point} scaleMax */ scaleMax: null, /** * Adjust scaling limits, if set, to this Game Object. * * @method * @private * @param {PIXI.Matrix} wt - The updated worldTransform matrix. */ checkTransform: function (wt) { if (this.scaleMin) { if (wt.a < this.scaleMin.x) { wt.a = this.scaleMin.x; } if (wt.d < this.scaleMin.y) { wt.d = this.scaleMin.y; } } if (this.scaleMax) { if (wt.a > this.scaleMax.x) { wt.a = this.scaleMax.x; } if (wt.d > this.scaleMax.y) { wt.d = this.scaleMax.y; } } }, /** * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent. * * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to. * * By setting these values you can carefully control how Game Objects deal with responsive scaling. * * If only one parameter is given then that value will be used for both scaleMin and scaleMax: * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1 * * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y: * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2 * * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly, * or pass `null` for the `maxX` and `maxY` parameters. * * Call `setScaleMinMax(null)` to clear all previously set values. * * @method * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to. * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to. * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to. * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to. */ setScaleMinMax: function (minX, minY, maxX, maxY) { if (minY === undefined) { // 1 parameter, set all to it minY = maxX = maxY = minX; } else if (maxX === undefined) { // 2 parameters, the first is min, the second max maxX = maxY = minY; minY = minX; } if (minX === null) { this.scaleMin = null; } else { if (this.scaleMin) { this.scaleMin.set(minX, minY); } else { this.scaleMin = new Phaser.Point(minX, minY); } } if (maxX === null) { this.scaleMax = null; } else { if (this.scaleMax) { this.scaleMax.set(maxX, maxY); } else { this.scaleMax = new Phaser.Point(maxX, maxY); } } if (this.scaleMin === null) { this.transformCallback = null; } else { this.transformCallback = this.checkTransform; this.transformCallbackContext = this; } } }; /** * @author Richard Davey <rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Smoothed component allows a Game Object to control anti-aliasing of an image based texture. * * @class */ Phaser.Component.Smoothed = function () {}; Phaser.Component.Smoothed.prototype = { /** * Enable or disable texture smoothing for this Game Object. * * It only takes effect if the Game Object is using an image based texture. * * Smoothing is enabled by default. * * @property {boolean} smoothed */ smoothed: { get: function () { return !this.texture.baseTexture.scaleMode; }, set: function (value) { if (value) { if (this.texture) { this.texture.baseTexture.scaleMode = 0; } } else { if (this.texture) { this.texture.baseTexture.scaleMode = 1; } } } } };
/* global QUnit */ // import { ShapePath } from '../../../../../src/extras/core/ShapePath.js'; export default QUnit.module( 'Extras', () => { QUnit.module( 'Core', () => { QUnit.module( 'ShapePath', () => { // INSTANCING QUnit.todo( 'Instancing', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); // PUBLIC STUFF QUnit.todo( 'moveTo', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); QUnit.todo( 'lineTo', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); QUnit.todo( 'quadraticCurveTo', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); QUnit.todo( 'bezierCurveTo', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); QUnit.todo( 'splineThru', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); QUnit.todo( 'toShapes', ( assert ) => { assert.ok( false, 'everything\'s gonna be alright' ); } ); } ); } ); } );
module.exports = str /** * Returns a string representation of a mat3 * * @alias mat3.str * @param {mat3} mat matrix to represent as a string * @returns {String} string representation of the matrix */ function str(a) { return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ')' }
'use strict'; const common = require('../common'); const assert = require('assert'); assert.throws( () => process.setUncaughtExceptionCaptureCallback(42), { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', message: 'The "fn" argument must be of type function or null. ' + 'Received type number (42)' } ); process.setUncaughtExceptionCaptureCallback(common.mustNotCall()); assert.throws( () => process.setUncaughtExceptionCaptureCallback(common.mustNotCall()), { code: 'ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET', name: 'Error', message: /setupUncaughtExceptionCapture.*called while a capture callback/ } );
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file SciantificNumber.js * @author Yann yann@ethdev.com * @author Arkadiy Paronyan arkadiy@ethdev.com * @date 2015 * Ethereum IDE client. */ function isScientificNumber(_value) { var nbRegEx = new RegExp('^[0-9]+$'); var n = _value.toLowerCase().split("e") if (n.length === 2) return nbRegEx.test(n[0].replace(".", "")) && nbRegEx.test(n[1].replace("-", "")); return false } function isNumber(_value) { if (!_value) return false if (!isNaN(_value)) _value = _value.toString(); var nbRegEx = new RegExp('^[0-9]+$'); return nbRegEx.test(_value.replace(/"/g, "").replace(/'/g, "").replace(".", "")) } function toFlatNumber(_value) { var s = _value.split("e") var e = parseInt(s[1]) var number = s[0] var floatValue; if (number.indexOf(".") !== -1) floatValue = number.split(".") else floatValue = [ number , "" ] var k = 0 var floatPos = floatValue[0].length var d = e > 0 ? 1 : -1 var n = floatValue[0] + floatValue[1] while (k < Math.abs(e)) { floatPos = floatPos + d if (floatPos <= 0) n = "0" + n else if (floatPos > n.length) n = n + "0" k++ } var ret = n.slice(0, floatPos < 0 ? 1 : Math.abs(floatPos)) + "." + n.slice(floatPos < 0 ? 1 : Math.abs(floatPos)); if (ret.indexOf(".") === ret.length - 1) ret = ret.replace(".", "") return normalize(ret) } function removeTrailingZero(_value) { var j = _value.length - 1 while (j >= 0) { if (_value[j] !== "0") break j-- } return _value.substring(0, j) } function removeLeadingZero(_value) { var j = 0 while (j < _value.length) { if (_value[j] !== "0") break j++ } return _value.substring(j) } function normalize(_value) { if (!isNaN(_value)) _value = _value.toString() var val = _value var splitted = _value.split(".") if (splitted.length > 1) { if (splitted[0].replace(/0/g, "") === "") val = "0." + removeTrailingZero(splitted[1]) else val = removeLeadingZero(splitted[0]) + "." + removeTrailingZero(splitted[1]) } else return removeLeadingZero(_value) } function toScientificNumber(_value) { var val = normalize(_value) if (val.indexOf(".") !== -1) val = _value.replace(".", "") var k = 0 var zeroPos = {} zeroPos[0] = 0 var current = 0 while (k < val.length) { if (val[k] !== "0") { zeroPos[k] = 0 current = k } else zeroPos[current]++ k++ } var ret; if (val.indexOf("0") === 0) ret = val.substring(zeroPos[0]) + "e-" + zeroPos[0] else ret = val.substring(0, current + 1) + "e" + zeroPos[current] return ret } function shouldConvertToScientific(_value) { return isNumber(_value) && normalize(_value).length > 7 }
import { extend } from 'flarum/extend'; import Page from 'flarum/components/Page'; import ItemList from 'flarum/utils/ItemList'; import listItems from 'flarum/helpers/listItems'; import icon from 'flarum/helpers/icon'; import DiscussionList from 'flarum/components/DiscussionList'; import WelcomeHero from 'flarum/components/WelcomeHero'; import DiscussionComposer from 'flarum/components/DiscussionComposer'; import LogInModal from 'flarum/components/LogInModal'; import DiscussionPage from 'flarum/components/DiscussionPage'; import Select from 'flarum/components/Select'; import Button from 'flarum/components/Button'; import LinkButton from 'flarum/components/LinkButton'; import SelectDropdown from 'flarum/components/SelectDropdown'; /** * The `IndexPage` component displays the index page, including the welcome * hero, the sidebar, and the discussion list. */ export default class IndexPage extends Page { init() { super.init(); // If the user is returning from a discussion page, then take note of which // discussion they have just visited. After the view is rendered, we will // scroll down so that this discussion is in view. if (app.previous instanceof DiscussionPage) { this.lastDiscussion = app.previous.discussion; } // If the user is coming from the discussion list, then they have either // just switched one of the parameters (filter, sort, search) or they // probably want to refresh the results. We will clear the discussion list // cache so that results are reloaded. if (app.previous instanceof IndexPage) { app.cache.discussionList = null; } const params = this.params(); if (app.cache.discussionList) { // Compare the requested parameters (sort, search query) to the ones that // are currently present in the cached discussion list. If they differ, we // will clear the cache and set up a new discussion list component with // the new parameters. Object.keys(params).some(key => { if (app.cache.discussionList.props.params[key] !== params[key]) { app.cache.discussionList = null; return true; } }); } if (!app.cache.discussionList) { app.cache.discussionList = new DiscussionList({params}); } app.history.push('index', icon('bars')); this.bodyClass = 'App--index'; } onunload() { // Save the scroll position so we can restore it when we return to the // discussion list. app.cache.scrollTop = $(window).scrollTop(); } view() { return ( <div className="IndexPage"> {this.hero()} <div className="container"> <nav className="IndexPage-nav sideNav"> <ul>{listItems(this.sidebarItems().toArray())}</ul> </nav> <div className="IndexPage-results sideNavOffset"> <div className="IndexPage-toolbar"> <ul className="IndexPage-toolbar-view">{listItems(this.viewItems().toArray())}</ul> <ul className="IndexPage-toolbar-action">{listItems(this.actionItems().toArray())}</ul> </div> {app.cache.discussionList.render()} </div> </div> </div> ); } config(isInitialized, context) { super.config(...arguments); if (isInitialized) return; extend(context, 'onunload', () => $('#app').css('min-height', '')); app.setTitle(''); app.setTitleCount(0); // Work out the difference between the height of this hero and that of the // previous hero. Maintain the same scroll position relative to the bottom // of the hero so that the sidebar doesn't jump around. const oldHeroHeight = app.cache.heroHeight; const heroHeight = app.cache.heroHeight = this.$('.Hero').outerHeight(); const scrollTop = app.cache.scrollTop; $('#app').css('min-height', $(window).height() + heroHeight); // Scroll to the remembered position. We do this after a short delay so that // it happens after the browser has done its own "back button" scrolling, // which isn't right. https://github.com/flarum/core/issues/835 const scroll = () => $(window).scrollTop(scrollTop - oldHeroHeight + heroHeight); scroll(); setTimeout(scroll, 1); // If we've just returned from a discussion page, then the constructor will // have set the `lastDiscussion` property. If this is the case, we want to // scroll down to that discussion so that it's in view. if (this.lastDiscussion) { const $discussion = this.$(`.DiscussionListItem[data-id="${this.lastDiscussion.id()}"]`); if ($discussion.length) { const indexTop = $('#header').outerHeight(); const indexBottom = $(window).height(); const discussionTop = $discussion.offset().top; const discussionBottom = discussionTop + $discussion.outerHeight(); if (discussionTop < scrollTop + indexTop || discussionBottom > scrollTop + indexBottom) { $(window).scrollTop(discussionTop - indexTop); } } } } /** * Get the component to display as the hero. * * @return {MithrilComponent} */ hero() { return WelcomeHero.component(); } /** * Build an item list for the sidebar of the index page. By default this is a * "New Discussion" button, and then a DropdownSelect component containing a * list of navigation items. * * @return {ItemList} */ sidebarItems() { const items = new ItemList(); const canStartDiscussion = app.forum.attribute('canStartDiscussion') || !app.session.user; items.add('newDiscussion', Button.component({ children: app.translator.trans(canStartDiscussion ? 'core.forum.index.start_discussion_button' : 'core.forum.index.cannot_start_discussion_button'), icon: 'edit', className: 'Button Button--primary IndexPage-newDiscussion', itemClassName: 'App-primaryControl', onclick: this.newDiscussion.bind(this), disabled: !canStartDiscussion }) ); items.add('nav', SelectDropdown.component({ children: this.navItems(this).toArray(), buttonClassName: 'Button', className: 'App-titleControl' }) ); return items; } /** * Build an item list for the navigation in the sidebar of the index page. By * default this is just the 'All Discussions' link. * * @return {ItemList} */ navItems() { const items = new ItemList(); const params = this.stickyParams(); items.add('allDiscussions', LinkButton.component({ href: app.route('index', params), children: app.translator.trans('core.forum.index.all_discussions_link'), icon: 'comments-o' }), 100 ); return items; } /** * Build an item list for the part of the toolbar which is concerned with how * the results are displayed. By default this is just a select box to change * the way discussions are sorted. * * @return {ItemList} */ viewItems() { const items = new ItemList(); const sortMap = app.cache.discussionList.sortMap(); const sortOptions = {}; for (const i in sortMap) { sortOptions[i] = app.translator.trans('core.forum.index_sort.' + i + '_button'); } items.add('sort', Select.component({ options: sortOptions, value: this.params().sort || Object.keys(sortMap)[0], onchange: this.changeSort.bind(this) }) ); return items; } /** * Build an item list for the part of the toolbar which is about taking action * on the results. By default this is just a "mark all as read" button. * * @return {ItemList} */ actionItems() { const items = new ItemList(); items.add('refresh', Button.component({ title: app.translator.trans('core.forum.index.refresh_tooltip'), icon: 'refresh', className: 'Button Button--icon', onclick: () => app.cache.discussionList.refresh() }) ); if (app.session.user) { items.add('markAllAsRead', Button.component({ title: app.translator.trans('core.forum.index.mark_all_as_read_tooltip'), icon: 'check', className: 'Button Button--icon', onclick: this.markAllAsRead.bind(this) }) ); } return items; } /** * Return the current search query, if any. This is implemented to activate * the search box in the header. * * @see Search * @return {String} */ searching() { return this.params().q; } /** * Redirect to the index page without a search filter. This is called when the * 'x' is clicked in the search box in the header. * * @see Search */ clearSearch() { const params = this.params(); delete params.q; m.route(app.route(this.props.routeName, params)); } /** * Redirect to the index page using the given sort parameter. * * @param {String} sort */ changeSort(sort) { const params = this.params(); if (sort === Object.keys(app.cache.discussionList.sortMap())[0]) { delete params.sort; } else { params.sort = sort; } m.route(app.route(this.props.routeName, params)); } /** * Get URL parameters that stick between filter changes. * * @return {Object} */ stickyParams() { return { sort: m.route.param('sort'), q: m.route.param('q') }; } /** * Get parameters to pass to the DiscussionList component. * * @return {Object} */ params() { const params = this.stickyParams(); params.filter = m.route.param('filter'); return params; } /** * Log the user in and then open the composer for a new discussion. * * @return {Promise} */ newDiscussion() { const deferred = m.deferred(); if (app.session.user) { this.composeNewDiscussion(deferred); } else { app.modal.show( new LogInModal({ onlogin: this.composeNewDiscussion.bind(this, deferred) }) ); } return deferred.promise; } /** * Initialize the composer for a new discussion. * * @param {Deferred} deferred * @return {Promise} */ composeNewDiscussion(deferred) { const component = new DiscussionComposer({user: app.session.user}); app.composer.load(component); app.composer.show(); deferred.resolve(component); return deferred.promise; } /** * Mark all discussions as read. * * @return void */ markAllAsRead() { const confirmation = confirm(app.translator.trans('core.forum.index.mark_all_as_read_confirmation')); if (confirmation) { app.session.user.save({readTime: new Date()}); } } }
// flow-typed signature: f7bf040869842c4af9aa8e5e72c252fa // flow-typed version: e1ccfebf85/bluebird_v3.x.x/flow_>=v0.32.x type Bluebird$RangeError = Error; type Bluebird$CancellationErrors = Error; type Bluebird$TimeoutError = Error; type Bluebird$RejectionError = Error; type Bluebird$OperationalError = Error; type Bluebird$ConcurrencyOption = { concurrency: number, }; type Bluebird$SpreadOption = { spread: boolean; }; type Bluebird$MultiArgsOption = { multiArgs: boolean; }; type Bluebird$BluebirdConfig = { warnings?: boolean, longStackTraces?: boolean, cancellation?: boolean, monitoring?: boolean }; declare class Bluebird$PromiseInspection<T> { isCancelled(): bool; isFulfilled(): bool; isRejected(): bool; pending(): bool; reason(): any; value(): T; } type Bluebird$PromisifyOptions = {| multiArgs?: boolean, context: any |}; declare type Bluebird$PromisifyAllOptions = { suffix?: string; filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; // The promisifier gets a reference to the original method and should return a function which returns a promise promisifier?: (originalMethod: Function) => () => Bluebird$Promise<any> ; }; declare type Bluebird$Promisable<T> = Bluebird$Promise<T> | Promise<T> | T; declare class Bluebird$Promise<R> { static Defer: Class<Bluebird$Defer>; static PromiseInspection: Class<Bluebird$PromiseInspection<*>>; static all<T, Elem: Bluebird$Promisable<T>>(Promises: Array<Elem>): Bluebird$Promise<Array<T>>; static props(input: Bluebird$Promisable<Object|Map<*,*>>): Bluebird$Promise<*>; static any<T, Elem: Bluebird$Promisable<T>>(Promises: Array<Elem>): Bluebird$Promise<T>; static race<T, Elem: Bluebird$Promisable<T>>(Promises: Array<Elem>): Bluebird$Promise<T>; static reject<T>(error?: any): Bluebird$Promise<T>; static resolve<T>(object?: Bluebird$Promisable<T>): Bluebird$Promise<T>; static some<T, Elem: Bluebird$Promisable<T>>(Promises: Array<Elem>, count: number): Bluebird$Promise<Array<T>>; static join<T, Elem: Bluebird$Promisable<T>>(...Promises: Array<Elem>): Bluebird$Promise<Array<T>>; static map<T, U, Elem: Bluebird$Promisable<T>>( Promises: Array<Elem>, mapper: (item: T, index: number, arrayLength: number) => U, options?: Bluebird$ConcurrencyOption ): Bluebird$Promise<Array<U>>; static mapSeries<T, U, Elem: Bluebird$Promisable<T>>( Promises: Array<Elem>, mapper: (item: T, index: number, arrayLength: number) => U ): Bluebird$Promise<Array<U>>; static reduce<T, U, Elem: Bluebird$Promisable<T>>( Promises: Array<Elem>, reducer: (total: U, current: T, index: number, arrayLength: number) => U, initialValue?: U ): Bluebird$Promise<U>; static filter<T, Elem: Bluebird$Promisable<T>>( Promises: Array<Elem>, filterer: (item: T, index: number, arrayLength: number) => Bluebird$Promisable<bool>, option?: Bluebird$ConcurrencyOption ): Bluebird$Promise<Array<T>>; static each<T, Elem: Bluebird$Promisable<T>>( Promises: Array<Elem>, iterator: (item: T, index: number, arrayLength: number) => Bluebird$Promisable<mixed>, ): Bluebird$Promise<Array<T>>; static try<T>(fn: () => Bluebird$Promisable<T>, args: ?Array<any>, ctx: ?any): Bluebird$Promise<T>; static attempt<T>(fn: () => Bluebird$Promisable<T>, args: ?Array<any>, ctx: ?any): Bluebird$Promise<T>; static delay<T>(value: Bluebird$Promisable<T>, ms: number): Bluebird$Promise<T>; static delay(ms: number): Bluebird$Promise<void>; static config(config: Bluebird$BluebirdConfig): void; static defer(): Bluebird$Defer; static setScheduler(scheduler: (callback: (...args: Array<any>) => void) => void): void; static promisify(nodeFunction: Function, receiver?: Bluebird$PromisifyOptions): Function; static promisifyAll(target: Object, options?: Bluebird$PromisifyAllOptions): void; static coroutine(generatorFunction: Function): Function; static spawn<T>(generatorFunction: Function): Promise<T>; // It doesn't seem possible to have type-generics for a variable number of arguments. // Handle up to 3 arguments, then just give up and accept 'any'. static method<T>(fn: () => T): () => Bluebird$Promise<T>; static method<T, A>(fn: (a: A) => T): (a: A) => Bluebird$Promise<T>; static method<T, A, B>(fn: (a: A, b: B) => T): (a: A, b: B) => Bluebird$Promise<T>; static method<T, A, B, C>(fn: (a: A, b: B, c: B) => T): (a: A, b: B, c: B) => Bluebird$Promise<T>; static method<T>(fn: (...args: any) => T): (...args: any) => Bluebird$Promise<T>; static cast<T>(value: Bluebird$Promisable<T>): Bluebird$Promise<T>; static bind(ctx: any): Bluebird$Promise<void>; static is(value: any): boolean; static longStackTraces(): void; static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; static fromCallback<T>(resolver: (fn: (error: ?Error, value?: T) => any) => any, options?: Bluebird$MultiArgsOption): Bluebird$Promise<T>; constructor(callback: ( resolve: (result?: Bluebird$Promisable<R>) => void, reject: (error?: any) => void ) => mixed): void; then<U>(onFulfill?: (value: R) => Bluebird$Promisable<U>, onReject?: (error: any) => Bluebird$Promisable<U>): Bluebird$Promise<U>; catch<U>(onReject?: (error: any) => ?Bluebird$Promisable<U>): Bluebird$Promise<U>; caught<U>(onReject?: (error: any) => ?Bluebird$Promisable<U>): Bluebird$Promise<U>; error<U>(onReject?: (error: any) => ?Bluebird$Promisable<U>): Bluebird$Promise<U>; done<U>(onFulfill?: (value: R) => mixed, onReject?: (error: any) => mixed): void; finally<T>(onDone?: (value: R) => mixed): Bluebird$Promise<T>; lastly<T>(onDone?: (value: R) => mixed): Bluebird$Promise<T>; tap<T>(onDone?: (value: R) => mixed): Bluebird$Promise<T>; delay(ms: number): Bluebird$Promise<R>; timeout(ms: number, message?: string): Bluebird$Promise<R>; cancel(): void; bind(ctx: any): Bluebird$Promise<R>; call(propertyName: string, ...args: Array<any>): Bluebird$Promise<any>; throw(reason: Error): Bluebird$Promise<R>; thenThrow(reason: Error): Bluebird$Promise<R>; all<T>(): Bluebird$Promise<Array<T>>; any<T>(): Bluebird$Promise<T>; some<T>(count: number): Bluebird$Promise<Array<T>>; race<T>(): Bluebird$Promise<T>; map<T, U>(mapper: (item: T, index: number, arrayLength: number) => Bluebird$Promisable<U>, options?: Bluebird$ConcurrencyOption): Bluebird$Promise<Array<U>>; mapSeries<T, U>(mapper: (item: T, index: number, arrayLength: number) => Bluebird$Promisable<U>): Bluebird$Promise<Array<U>>; reduce<T, U>( reducer: (total: T, item: U, index: number, arrayLength: number) => Bluebird$Promisable<T>, initialValue?: T ): Bluebird$Promise<T>; filter<T>(filterer: (item: T, index: number, arrayLength: number) => Bluebird$Promisable<bool>, options?: Bluebird$ConcurrencyOption): Bluebird$Promise<Array<T>>; each<T, U>(iterator: (item: T, index: number, arrayLength: number) => Bluebird$Promisable<U>): Bluebird$Promise<Array<T>>; asCallback<T>(callback: (error: ?any, value?: T) => any, options?: Bluebird$SpreadOption): void; return<T>(value: T): Bluebird$Promise<T>; reflect(): Bluebird$Promise<Bluebird$PromiseInspection<*>>; isFulfilled(): bool; isRejected(): bool; isPending(): bool; isResolved(): bool; value(): R; reason(): any; } declare class Bluebird$Defer { promise: Bluebird$Promise<*>; resolve: (value: any) => any; reject: (value: any) => any; } declare module 'bluebird' { declare var exports: typeof Bluebird$Promise; }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _timesLimit = require('./timesLimit'); var _timesLimit2 = _interopRequireDefault(_timesLimit); var _doLimit = require('./internal/doLimit'); var _doLimit2 = _interopRequireDefault(_doLimit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Calls the `iteratee` function `n` times, and accumulates results in the same * manner you would use with [map]{@link module:Collections.map}. * * @name times * @static * @memberOf module:ControlFlow * @method * @see [async.map]{@link module:Collections.map} * @category Control Flow * @param {number} n - The number of times to run the function. * @param {AsyncFunction} iteratee - The async function to call `n` times. * Invoked with the iteration index and a callback: (n, next). * @param {Function} callback - see {@link module:Collections.map}. * @example * * // Pretend this is some complicated async factory * var createUser = function(id, callback) { * callback(null, { * id: 'user' + id * }); * }; * * // generate 5 users * async.times(5, function(n, next) { * createUser(n, function(err, user) { * next(err, user); * }); * }, function(err, users) { * // we should now have 5 users * }); */ exports.default = (0, _doLimit2.default)(_timesLimit2.default, Infinity); module.exports = exports['default'];
import { test } from 'qunit'; [ true, false ].forEach( modifyArrays => { test( `ractive.reverse() (modifyArrays: ${modifyArrays})`, t => { let items = [ 'alice', 'bob', 'charles' ]; const ractive = new Ractive({ el: fixture, template: ` <ul> {{#items}} <li>{{.}}</li> {{/items}} </ul>`, data: { items } }); ractive.reverse( 'items' ); t.htmlEqual( fixture.innerHTML, '<ul><li>charles</li><li>bob</li><li>alice</li></ul>' ); }); });
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import fs from 'fs'; import path from 'path'; import glob from 'glob'; import mkdirp from 'mkdirp'; import rimraf from 'rimraf'; export const readFile = (file) => new Promise((resolve, reject) => { fs.readFile(file, 'utf8', (err, data) => (err ? reject(err) : resolve(data))); }); export const writeFile = (file, contents) => new Promise((resolve, reject) => { fs.writeFile(file, contents, 'utf8', err => (err ? reject(err) : resolve())); }); export const copyFile = (source, target) => new Promise((resolve, reject) => { let cbCalled = false; function done(err) { if (!cbCalled) { cbCalled = true; if (err) { reject(err); } else { resolve(); } } } const rd = fs.createReadStream(source); rd.on('error', err => done(err)); const wr = fs.createWriteStream(target); wr.on('error', err => done(err)); wr.on('close', err => done(err)); rd.pipe(wr); }); export const readDir = (pattern, options) => new Promise((resolve, reject) => glob(pattern, options, (err, result) => (err ? reject(err) : resolve(result))), ); export const makeDir = (name) => new Promise((resolve, reject) => { mkdirp(name, err => (err ? reject(err) : resolve())); }); export const copyDir = async (source, target) => { const dirs = await readDir('**/*.*', { cwd: source, nosort: true, dot: true, }); await Promise.all(dirs.map(async dir => { const from = path.resolve(source, dir); const to = path.resolve(target, dir); await makeDir(path.dirname(to)); await copyFile(from, to); })); }; export const cleanDir = (pattern, options) => new Promise((resolve, reject) => rimraf(pattern, { glob: options }, (err, result) => (err ? reject(err) : resolve(result))), );
// Copyright 2008 The Closure Library Authors. 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. /** * @fileoverview Implementation of sprintf-like, python-%-operator-like, * .NET-String.Format-like functionality. Uses JS string's replace method to * extract format specifiers and sends those specifiers to a handler function, * which then, based on conversion type part of the specifier, calls the * appropriate function to handle the specific conversion. * For specific functionality implemented, look at formatRe below, or look * at the tests. */ goog.provide('goog.string.format'); goog.require('goog.string'); /** * Performs sprintf-like conversion, i.e. puts the values in a template. * DO NOT use it instead of built-in conversions in simple cases such as * 'Cost: %.2f' as it would introduce unnecessary latency opposed to * 'Cost: ' + cost.toFixed(2). * @param {string} formatString Template string containing % specifiers. * @param {...string|number} var_args Values formatString is to be filled with. * @return {string} Formatted string. */ goog.string.format = function(formatString, var_args) { // Convert the arguments to an array (MDC recommended way). var args = Array.prototype.slice.call(arguments); // Try to get the template. var template = args.shift(); if (typeof template == 'undefined') { throw Error('[goog.string.format] Template required'); } // This re is used for matching, it also defines what is supported. var formatRe = /%([0\-\ \+]*)(\d+)?(\.(\d+))?([%sfdiu])/g; /** * Chooses which conversion function to call based on type conversion * specifier. * @param {string} match Contains the re matched string. * @param {string} flags Formatting flags. * @param {string} width Replacement string minimum width. * @param {string} dotp Matched precision including a dot. * @param {string} precision Specifies floating point precision. * @param {string} type Type conversion specifier. * @param {string} offset Matching location in the original string. * @param {string} wholeString Has the actualString being searched. * @return {string} Formatted parameter. */ function replacerDemuxer( match, flags, width, dotp, precision, type, offset, wholeString) { // The % is too simple and doesn't take an argument. if (type == '%') { return '%'; } // Try to get the actual value from parent function. var value = args.shift(); // If we didn't get any arguments, fail. if (typeof value == 'undefined') { throw Error('[goog.string.format] Not enough arguments'); } // Patch the value argument to the beginning of our type specific call. arguments[0] = value; return goog.string.format.demuxes_[type].apply(null, arguments); } return template.replace(formatRe, replacerDemuxer); }; /** * Contains various conversion functions (to be filled in later on). * @private {!Object} */ goog.string.format.demuxes_ = {}; /** * Processes %s conversion specifier. * @param {string} value Contains the formatRe matched string. * @param {string} flags Formatting flags. * @param {string} width Replacement string minimum width. * @param {string} dotp Matched precision including a dot. * @param {string} precision Specifies floating point precision. * @param {string} type Type conversion specifier. * @param {string} offset Matching location in the original string. * @param {string} wholeString Has the actualString being searched. * @return {string} Replacement string. */ goog.string.format.demuxes_['s'] = function( value, flags, width, dotp, precision, type, offset, wholeString) { var replacement = value; // If no padding is necessary we're done. // The check for '' is necessary because Firefox incorrectly provides the // empty string instead of undefined for non-participating capture groups, // and isNaN('') == false. if (isNaN(width) || width == '' || replacement.length >= Number(width)) { return replacement; } // Otherwise we should find out where to put spaces. if (flags.indexOf('-', 0) > -1) { replacement = replacement + goog.string.repeat(' ', Number(width) - replacement.length); } else { replacement = goog.string.repeat(' ', Number(width) - replacement.length) + replacement; } return replacement; }; /** * Processes %f conversion specifier. * @param {string} value Contains the formatRe matched string. * @param {string} flags Formatting flags. * @param {string} width Replacement string minimum width. * @param {string} dotp Matched precision including a dot. * @param {string} precision Specifies floating point precision. * @param {string} type Type conversion specifier. * @param {string} offset Matching location in the original string. * @param {string} wholeString Has the actualString being searched. * @return {string} Replacement string. */ goog.string.format.demuxes_['f'] = function( value, flags, width, dotp, precision, type, offset, wholeString) { var replacement = value.toString(); // The check for '' is necessary because Firefox incorrectly provides the // empty string instead of undefined for non-participating capture groups, // and isNaN('') == false. if (!(isNaN(precision) || precision == '')) { replacement = parseFloat(value).toFixed(precision); } // Generates sign string that will be attached to the replacement. var sign; if (Number(value) < 0) { sign = '-'; } else if (flags.indexOf('+') >= 0) { sign = '+'; } else if (flags.indexOf(' ') >= 0) { sign = ' '; } else { sign = ''; } if (Number(value) >= 0) { replacement = sign + replacement; } // If no padding is neccessary we're done. if (isNaN(width) || replacement.length >= Number(width)) { return replacement; } // We need a clean signless replacement to start with replacement = isNaN(precision) ? Math.abs(Number(value)).toString() : Math.abs(Number(value)).toFixed(precision); var padCount = Number(width) - replacement.length - sign.length; // Find out which side to pad, and if it's left side, then which character to // pad, and set the sign on the left and padding in the middle. if (flags.indexOf('-', 0) >= 0) { replacement = sign + replacement + goog.string.repeat(' ', padCount); } else { // Decides which character to pad. var paddingChar = (flags.indexOf('0', 0) >= 0) ? '0' : ' '; replacement = sign + goog.string.repeat(paddingChar, padCount) + replacement; } return replacement; }; /** * Processes %d conversion specifier. * @param {string} value Contains the formatRe matched string. * @param {string} flags Formatting flags. * @param {string} width Replacement string minimum width. * @param {string} dotp Matched precision including a dot. * @param {string} precision Specifies floating point precision. * @param {string} type Type conversion specifier. * @param {string} offset Matching location in the original string. * @param {string} wholeString Has the actualString being searched. * @return {string} Replacement string. */ goog.string.format.demuxes_['d'] = function( value, flags, width, dotp, precision, type, offset, wholeString) { return goog.string.format.demuxes_['f']( parseInt(value, 10) /* value */, flags, width, dotp, 0 /* precision */, type, offset, wholeString); }; // These are additional aliases, for integer conversion. goog.string.format.demuxes_['i'] = goog.string.format.demuxes_['d']; goog.string.format.demuxes_['u'] = goog.string.format.demuxes_['d'];
var packpath = require('../../../../../') , path = require('path'); module.exports.selfFromPackPath = function() { return packpath.self(); } module.exports.self = function() { return path.resolve(__dirname); } module.exports.parentFromPackPath = function() { return packpath.parent(); } module.exports.parent = function() { return path.resolve(path.join(__dirname, '../../')); }
(function () { 'use strict'; function MediaNodeInfoDirective($timeout, $location, $q, eventsService, userService, dateHelper, editorService, mediaHelper, mediaResource) { function link(scope, element, attrs, ctrl) { var evts = []; scope.allowChangeMediaType = false; scope.loading = true; scope.changeContentPageNumber = changeContentPageNumber; scope.contentOptions = {}; scope.contentOptions.entityType = "DOCUMENT"; scope.hasContentReferences = false; scope.changeMediaPageNumber = changeMediaPageNumber; scope.mediaOptions = {}; scope.mediaOptions.entityType = "MEDIA"; scope.hasMediaReferences = false; scope.changeMemberPageNumber = changeMemberPageNumber; scope.memberOptions = {}; scope.memberOptions.entityType = "MEMBER"; scope.hasMemberReferences = false; function onInit() { userService.getCurrentUser().then(user => { // only allow change of media type if user has access to the settings sections Utilities.forEach(user.sections, section => { if (section.alias === "settings") { scope.allowChangeMediaType = true; } }); }); // get media type details scope.mediaType = scope.node.contentType; // set the media link initially setMediaLink(); // make sure dates are formatted to the user's locale formatDatesToLocal(); // set media file extension initially setMediaExtension(); } function formatDatesToLocal() { // get current backoffice user and format dates userService.getCurrentUser().then(currentUser => { scope.node.createDateFormatted = dateHelper.getLocalDate(scope.node.createDate, currentUser.locale, 'LLL'); scope.node.updateDateFormatted = dateHelper.getLocalDate(scope.node.updateDate, currentUser.locale, 'LLL'); }); } function setMediaLink(){ scope.nodeUrl = scope.node.mediaLink; // grab the file name from the URL and use it as the display name in the file link var match = /.*\/(.*)/.exec(scope.nodeUrl); if (match) { scope.nodeFileName = match[1]; } else { scope.nodeFileName = scope.nodeUrl; } } function setMediaExtension() { scope.node.extension = mediaHelper.getFileExtension(scope.nodeUrl); } scope.openMediaType = mediaType => { var editor = { id: mediaType.id, submit: model => { editorService.close(); }, close: () => { editorService.close(); } }; editorService.mediaTypeEditor(editor); }; scope.openSVG = () => { var popup = window.open('', '_blank'); var html = '<!DOCTYPE html><body><img src="' + scope.nodeUrl + '"/>' + '<script>history.pushState(null, null,"' + $location.$$absUrl + '");</script></body>'; popup.document.open(); popup.document.write(html); popup.document.close(); } // watch for content updates - reload content when node is saved, published etc. scope.$watch('node.updateDate', function(newValue, oldValue){ if(!newValue) { return; } if(newValue === oldValue) { return; } // Update the media link setMediaLink(); // Update the create and update dates formatDatesToLocal(); //Update the media file format setMediaExtension(); }); function changeContentPageNumber(pageNumber) { scope.contentOptions.pageNumber = pageNumber; loadContentRelations(); } function changeMediaPageNumber(pageNumber) { scope.mediaOptions.pageNumber = pageNumber; loadMediaRelations(); } function changeMemberPageNumber(pageNumber) { scope.memberOptions.pageNumber = pageNumber; loadMemberRelations(); } function loadContentRelations() { return mediaResource.getPagedReferences(scope.node.id, scope.contentOptions) .then(function (data) { scope.contentReferences = data; scope.hasContentReferences = data.items.length > 0; }); } function loadMediaRelations() { return mediaResource.getPagedReferences(scope.node.id, scope.mediaOptions) .then(data => { scope.mediaReferences = data; scope.hasMediaReferences = data.items.length > 0; }); } function loadMemberRelations() { return mediaResource.getPagedReferences(scope.node.id, scope.memberOptions) .then(data => { scope.memberReferences = data; scope.hasMemberReferences = data.items.length > 0; }); } //ensure to unregister from all events! scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); onInit(); // load media type references when the 'info' tab is first activated/switched to evts.push(eventsService.on("app.tabChange", function (event, args) { $timeout(function () { if (args.alias === "umbInfo") { $q.all([loadContentRelations(), loadMediaRelations(), loadMemberRelations()]).then(function () { scope.loading = false; }); } }); })); } var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/media/umb-media-node-info.html', scope: { node: "=" }, link: link }; return directive; } angular.module('umbraco.directives').directive('umbMediaNodeInfo', MediaNodeInfoDirective); })();
/* eslint no-unused-vars: "off" */ export default function (speed = this.params.speed, runCallbacks = true, internal) { const swiper = this; const { params, animating } = swiper; if (params.loop) { if (animating) return false; swiper.loopFix(); // eslint-disable-next-line swiper._clientLeft = swiper.$wrapperEl[0].clientLeft; return swiper.slideTo(swiper.activeIndex - 1, speed, runCallbacks, internal); } return swiper.slideTo(swiper.activeIndex - 1, speed, runCallbacks, internal); }
'use strict'; module.exports = function (gulp, $) { gulp.task('connect', [ 'clean:examples', 'scripts:setup', 'styles' ], function () { var livereloadPort = 35729; $.connect.server({ port: 9000, livereload: { port: livereloadPort }, root: 'examples', middleware: function (connect) { function mountFolder(connect, dir) { return connect.static(require('path').resolve(dir)); } return [ require('connect-livereload')({ port: livereloadPort }), mountFolder(connect, 'source'), mountFolder(connect, 'dist'), mountFolder(connect, 'bower_components'), mountFolder(connect, 'examples') ]; } }); }); gulp.task('watch', ['connect'], function () { gulp.watch([ '.jshintrc', 'source/**/*.js', 'examples/**/*.html' ], function (event) { return gulp.src(event.path) .pipe($.connect.reload()); }); gulp.watch([ '.jshintrc', 'source/**/*.js' ], ['jshint', 'jscs', 'clean:examples', 'scripts:setup']); gulp.watch([ 'source/**/*.scss' ], ['styles']); gulp.watch([ 'examples/**/*.scss' ], ['styles:examples']); }); gulp.task('open', ['connect'], function () { require('open')('http://localhost:9000'); }); };
export default { DATE_ROW_COUNT: 6, DATE_COL_COUNT: 7 };
const {createAddColumnMigration} = require('../../utils'); module.exports = createAddColumnMigration('posts', 'send_email_when_published', { type: 'bool', nullable: true, defaultTo: false });
// Generated by CoffeeScript 1.3.3 (function() { var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, some, starts, unfoldSoak, utility, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; Scope = require('./scope').Scope; _ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED; _ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last, some = _ref1.some; exports.extend = extend; YES = function() { return true; }; NO = function() { return false; }; THIS = function() { return this; }; NEGATE = function() { this.negated = !this.negated; return this; }; exports.Base = Base = (function() { function Base() {} Base.prototype.compile = function(o, lvl) { var node; o = extend({}, o); if (lvl) { o.level = lvl; } node = this.unfoldSoak(o) || this; node.tab = o.indent; if (o.level === LEVEL_TOP || !node.isStatement(o)) { return node.compileNode(o); } else { return node.compileClosure(o); } }; Base.prototype.compileClosure = function(o) { if (this.jumps()) { throw SyntaxError('cannot use a pure statement in an expression.'); } o.sharedScope = true; return Closure.wrap(this).compileNode(o); }; Base.prototype.cache = function(o, level, reused) { var ref, sub; if (!this.isComplex()) { ref = level ? this.compile(o, level) : this; return [ref, ref]; } else { ref = new Literal(reused || o.scope.freeVariable('ref')); sub = new Assign(ref, this); if (level) { return [sub.compile(o, level), ref.value]; } else { return [sub, ref]; } } }; Base.prototype.compileLoopReference = function(o, name) { var src, tmp; src = tmp = this.compile(o, LEVEL_LIST); if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) { src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src; } return [src, tmp]; }; Base.prototype.makeReturn = function(res) { var me; me = this.unwrapAll(); if (res) { return new Call(new Literal("" + res + ".push"), [me]); } else { return new Return(me); } }; Base.prototype.contains = function(pred) { var contains; contains = false; this.traverseChildren(false, function(node) { if (pred(node)) { contains = true; return false; } }); return contains; }; Base.prototype.containsType = function(type) { return this instanceof type || this.contains(function(node) { return node instanceof type; }); }; Base.prototype.lastNonComment = function(list) { var i; i = list.length; while (i--) { if (!(list[i] instanceof Comment)) { return list[i]; } } return null; }; Base.prototype.toString = function(idt, name) { var tree; if (idt == null) { idt = ''; } if (name == null) { name = this.constructor.name; } tree = '\n' + idt + name; if (this.soak) { tree += '?'; } this.eachChild(function(node) { return tree += node.toString(idt + TAB); }); return tree; }; Base.prototype.eachChild = function(func) { var attr, child, _i, _j, _len, _len1, _ref2, _ref3; if (!this.children) { return this; } _ref2 = this.children; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { attr = _ref2[_i]; if (this[attr]) { _ref3 = flatten([this[attr]]); for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { child = _ref3[_j]; if (func(child) === false) { return this; } } } } return this; }; Base.prototype.traverseChildren = function(crossScope, func) { return this.eachChild(function(child) { if (func(child) === false) { return false; } return child.traverseChildren(crossScope, func); }); }; Base.prototype.invert = function() { return new Op('!', this); }; Base.prototype.unwrapAll = function() { var node; node = this; while (node !== (node = node.unwrap())) { continue; } return node; }; Base.prototype.children = []; Base.prototype.isStatement = NO; Base.prototype.jumps = NO; Base.prototype.isComplex = YES; Base.prototype.isChainable = NO; Base.prototype.isAssignable = NO; Base.prototype.unwrap = THIS; Base.prototype.unfoldSoak = NO; Base.prototype.assigns = NO; return Base; })(); exports.Block = Block = (function(_super) { __extends(Block, _super); function Block(nodes) { this.expressions = compact(flatten(nodes || [])); } Block.prototype.children = ['expressions']; Block.prototype.push = function(node) { this.expressions.push(node); return this; }; Block.prototype.pop = function() { return this.expressions.pop(); }; Block.prototype.unshift = function(node) { this.expressions.unshift(node); return this; }; Block.prototype.unwrap = function() { if (this.expressions.length === 1) { return this.expressions[0]; } else { return this; } }; Block.prototype.isEmpty = function() { return !this.expressions.length; }; Block.prototype.isStatement = function(o) { var exp, _i, _len, _ref2; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { exp = _ref2[_i]; if (exp.isStatement(o)) { return true; } } return false; }; Block.prototype.jumps = function(o) { var exp, _i, _len, _ref2; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { exp = _ref2[_i]; if (exp.jumps(o)) { return exp; } } }; Block.prototype.makeReturn = function(res) { var expr, len; len = this.expressions.length; while (len--) { expr = this.expressions[len]; if (!(expr instanceof Comment)) { this.expressions[len] = expr.makeReturn(res); if (expr instanceof Return && !expr.expression) { this.expressions.splice(len, 1); } break; } } return this; }; Block.prototype.compile = function(o, level) { if (o == null) { o = {}; } if (o.scope) { return Block.__super__.compile.call(this, o, level); } else { return this.compileRoot(o); } }; Block.prototype.compileNode = function(o) { var code, codes, node, top, _i, _len, _ref2; this.tab = o.indent; top = o.level === LEVEL_TOP; codes = []; _ref2 = this.expressions; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { node = _ref2[_i]; node = node.unwrapAll(); node = node.unfoldSoak(o) || node; if (node instanceof Block) { codes.push(node.compileNode(o)); } else if (top) { node.front = true; code = node.compile(o); if (!node.isStatement(o)) { code = "" + this.tab + code + ";"; if (node instanceof Literal) { code = "" + code + "\n"; } } codes.push(code); } else { codes.push(node.compile(o, LEVEL_LIST)); } } if (top) { if (this.spaced) { return "\n" + (codes.join('\n\n')) + "\n"; } else { return codes.join('\n'); } } code = codes.join(', ') || 'void 0'; if (codes.length > 1 && o.level >= LEVEL_LIST) { return "(" + code + ")"; } else { return code; } }; Block.prototype.compileRoot = function(o) { var code, exp, i, prelude, preludeExps, rest; o.indent = o.bare ? '' : TAB; o.scope = new Scope(null, this, null); o.level = LEVEL_TOP; this.spaced = true; prelude = ""; if (!o.bare) { preludeExps = (function() { var _i, _len, _ref2, _results; _ref2 = this.expressions; _results = []; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { exp = _ref2[i]; if (!(exp.unwrap() instanceof Comment)) { break; } _results.push(exp); } return _results; }).call(this); rest = this.expressions.slice(preludeExps.length); this.expressions = preludeExps; if (preludeExps.length) { prelude = "" + (this.compileNode(merge(o, { indent: '' }))) + "\n"; } this.expressions = rest; } code = this.compileWithDeclarations(o); if (o.bare) { return code; } return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n"; }; Block.prototype.compileWithDeclarations = function(o) { var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4; code = post = ''; _ref2 = this.expressions; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { exp = _ref2[i]; exp = exp.unwrap(); if (!(exp instanceof Comment || exp instanceof Literal)) { break; } } o = merge(o, { level: LEVEL_TOP }); if (i) { rest = this.expressions.splice(i, 9e9); _ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1]; _ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1]; this.expressions = rest; } post = this.compileNode(o); scope = o.scope; if (scope.expressions === this) { declars = o.scope.hasDeclarations(); assigns = scope.hasAssignments; if (declars || assigns) { if (i) { code += '\n'; } code += "" + this.tab + "var "; if (declars) { code += scope.declaredVariables().join(', '); } if (assigns) { if (declars) { code += ",\n" + (this.tab + TAB); } code += scope.assignedVariables().join(",\n" + (this.tab + TAB)); } code += ';\n'; } } return code + post; }; Block.wrap = function(nodes) { if (nodes.length === 1 && nodes[0] instanceof Block) { return nodes[0]; } return new Block(nodes); }; return Block; })(Base); exports.Literal = Literal = (function(_super) { __extends(Literal, _super); function Literal(value) { this.value = value; } Literal.prototype.makeReturn = function() { if (this.isStatement()) { return this; } else { return Literal.__super__.makeReturn.apply(this, arguments); } }; Literal.prototype.isAssignable = function() { return IDENTIFIER.test(this.value); }; Literal.prototype.isStatement = function() { var _ref2; return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger'; }; Literal.prototype.isComplex = NO; Literal.prototype.assigns = function(name) { return name === this.value; }; Literal.prototype.jumps = function(o) { if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) { return this; } if (this.value === 'continue' && !(o != null ? o.loop : void 0)) { return this; } }; Literal.prototype.compileNode = function(o) { var code, _ref2; code = this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value; if (this.isStatement()) { return "" + this.tab + code + ";"; } else { return code; } }; Literal.prototype.toString = function() { return ' "' + this.value + '"'; }; return Literal; })(Base); exports.Undefined = (function(_super) { __extends(Undefined, _super); function Undefined() { return Undefined.__super__.constructor.apply(this, arguments); } Undefined.prototype.isAssignable = NO; Undefined.prototype.isComplex = NO; Undefined.prototype.compileNode = function(o) { if (o.level >= LEVEL_ACCESS) { return '(void 0)'; } else { return 'void 0'; } }; return Undefined; })(Base); exports.Null = (function(_super) { __extends(Null, _super); function Null() { return Null.__super__.constructor.apply(this, arguments); } Null.prototype.isAssignable = NO; Null.prototype.isComplex = NO; Null.prototype.compileNode = function() { return "null"; }; return Null; })(Base); exports.Bool = (function(_super) { __extends(Bool, _super); Bool.prototype.isAssignable = NO; Bool.prototype.isComplex = NO; Bool.prototype.compileNode = function() { return this.val; }; function Bool(val) { this.val = val; } return Bool; })(Base); exports.Return = Return = (function(_super) { __extends(Return, _super); function Return(expr) { if (expr && !expr.unwrap().isUndefined) { this.expression = expr; } } Return.prototype.children = ['expression']; Return.prototype.isStatement = YES; Return.prototype.makeReturn = THIS; Return.prototype.jumps = THIS; Return.prototype.compile = function(o, level) { var expr, _ref2; expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0; if (expr && !(expr instanceof Return)) { return expr.compile(o, level); } else { return Return.__super__.compile.call(this, o, level); } }; Return.prototype.compileNode = function(o) { return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";"); }; return Return; })(Base); exports.Value = Value = (function(_super) { __extends(Value, _super); function Value(base, props, tag) { if (!props && base instanceof Value) { return base; } this.base = base; this.properties = props || []; if (tag) { this[tag] = true; } return this; } Value.prototype.children = ['base', 'properties']; Value.prototype.add = function(props) { this.properties = this.properties.concat(props); return this; }; Value.prototype.hasProperties = function() { return !!this.properties.length; }; Value.prototype.isArray = function() { return !this.properties.length && this.base instanceof Arr; }; Value.prototype.isComplex = function() { return this.hasProperties() || this.base.isComplex(); }; Value.prototype.isAssignable = function() { return this.hasProperties() || this.base.isAssignable(); }; Value.prototype.isSimpleNumber = function() { return this.base instanceof Literal && SIMPLENUM.test(this.base.value); }; Value.prototype.isString = function() { return this.base instanceof Literal && IS_STRING.test(this.base.value); }; Value.prototype.isAtomic = function() { var node, _i, _len, _ref2; _ref2 = this.properties.concat(this.base); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { node = _ref2[_i]; if (node.soak || node instanceof Call) { return false; } } return true; }; Value.prototype.isStatement = function(o) { return !this.properties.length && this.base.isStatement(o); }; Value.prototype.assigns = function(name) { return !this.properties.length && this.base.assigns(name); }; Value.prototype.jumps = function(o) { return !this.properties.length && this.base.jumps(o); }; Value.prototype.isObject = function(onlyGenerated) { if (this.properties.length) { return false; } return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated); }; Value.prototype.isSplice = function() { return last(this.properties) instanceof Slice; }; Value.prototype.unwrap = function() { if (this.properties.length) { return this; } else { return this.base; } }; Value.prototype.cacheReference = function(o) { var base, bref, name, nref; name = last(this.properties); if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) { return [this, this]; } base = new Value(this.base, this.properties.slice(0, -1)); if (base.isComplex()) { bref = new Literal(o.scope.freeVariable('base')); base = new Value(new Parens(new Assign(bref, base))); } if (!name) { return [base, bref]; } if (name.isComplex()) { nref = new Literal(o.scope.freeVariable('name')); name = new Index(new Assign(nref, name.index)); nref = new Index(nref); } return [base.add(name), new Value(bref || base.base, [nref || name])]; }; Value.prototype.compileNode = function(o) { var code, prop, props, _i, _len; this.base.front = this.front; props = this.properties; code = this.base.compile(o, props.length ? LEVEL_ACCESS : null); if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) { code = "" + code + "."; } for (_i = 0, _len = props.length; _i < _len; _i++) { prop = props[_i]; code += prop.compile(o); } return code; }; Value.prototype.unfoldSoak = function(o) { var result, _this = this; if (this.unfoldedSoak != null) { return this.unfoldedSoak; } result = (function() { var fst, i, ifn, prop, ref, snd, _i, _len, _ref2; if (ifn = _this.base.unfoldSoak(o)) { Array.prototype.push.apply(ifn.body.properties, _this.properties); return ifn; } _ref2 = _this.properties; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { prop = _ref2[i]; if (!prop.soak) { continue; } prop.soak = false; fst = new Value(_this.base, _this.properties.slice(0, i)); snd = new Value(_this.base, _this.properties.slice(i)); if (fst.isComplex()) { ref = new Literal(o.scope.freeVariable('ref')); fst = new Parens(new Assign(ref, fst)); snd.base = ref; } return new If(new Existence(fst), snd, { soak: true }); } return null; })(); return this.unfoldedSoak = result || false; }; return Value; })(Base); exports.Comment = Comment = (function(_super) { __extends(Comment, _super); function Comment(comment) { this.comment = comment; } Comment.prototype.isStatement = YES; Comment.prototype.makeReturn = THIS; Comment.prototype.compileNode = function(o, level) { var code; code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n"); if ((level || o.level) === LEVEL_TOP) { code = o.indent + code; } return code; }; return Comment; })(Base); exports.Call = Call = (function(_super) { __extends(Call, _super); function Call(variable, args, soak) { this.args = args != null ? args : []; this.soak = soak; this.isNew = false; this.isSuper = variable === 'super'; this.variable = this.isSuper ? null : variable; } Call.prototype.children = ['variable', 'args']; Call.prototype.newInstance = function() { var base, _ref2; base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable; if (base instanceof Call && !base.isNew) { base.newInstance(); } else { this.isNew = true; } return this; }; Call.prototype.superReference = function(o) { var accesses, method, name; method = o.scope.namedMethod(); if (!method) { throw SyntaxError('cannot call super outside of a function.'); } name = method.name; if (name == null) { throw SyntaxError('cannot call super on an anonymous function.'); } if (method.klass) { accesses = [new Access(new Literal('__super__'))]; if (method["static"]) { accesses.push(new Access(new Literal('constructor'))); } accesses.push(new Access(new Literal(name))); return (new Value(new Literal(method.klass), accesses)).compile(o); } else { return "" + name + ".__super__.constructor"; } }; Call.prototype.superThis = function(o) { var method; method = o.scope.method; return (method && !method.klass && method.context) || "this"; }; Call.prototype.unfoldSoak = function(o) { var call, ifn, left, list, rite, _i, _len, _ref2, _ref3; if (this.soak) { if (this.variable) { if (ifn = unfoldSoak(o, this, 'variable')) { return ifn; } _ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1]; } else { left = new Literal(this.superReference(o)); rite = new Value(left); } rite = new Call(rite, this.args); rite.isNew = this.isNew; left = new Literal("typeof " + (left.compile(o)) + " === \"function\""); return new If(left, new Value(rite), { soak: true }); } call = this; list = []; while (true) { if (call.variable instanceof Call) { list.push(call); call = call.variable; continue; } if (!(call.variable instanceof Value)) { break; } list.push(call); if (!((call = call.variable.base) instanceof Call)) { break; } } _ref3 = list.reverse(); for (_i = 0, _len = _ref3.length; _i < _len; _i++) { call = _ref3[_i]; if (ifn) { if (call.variable instanceof Call) { call.variable = ifn; } else { call.variable.base = ifn; } } ifn = unfoldSoak(o, call, 'variable'); } return ifn; }; Call.prototype.filterImplicitObjects = function(list) { var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2; nodes = []; for (_i = 0, _len = list.length; _i < _len; _i++) { node = list[_i]; if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) { nodes.push(node); continue; } obj = null; _ref2 = node.base.properties; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { prop = _ref2[_j]; if (prop instanceof Assign || prop instanceof Comment) { if (!obj) { nodes.push(obj = new Obj(properties = [], true)); } properties.push(prop); } else { nodes.push(prop); obj = null; } } } return nodes; }; Call.prototype.compileNode = function(o) { var arg, args, code, _ref2; if ((_ref2 = this.variable) != null) { _ref2.front = this.front; } if (code = Splat.compileSplattedArray(o, this.args, true)) { return this.compileSplat(o, code); } args = this.filterImplicitObjects(this.args); args = ((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = args.length; _i < _len; _i++) { arg = args[_i]; _results.push(arg.compile(o, LEVEL_LIST)); } return _results; })()).join(', '); if (this.isSuper) { return this.superReference(o) + (".call(" + (this.superThis(o)) + (args && ', ' + args) + ")"); } else { return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")"); } }; Call.prototype.compileSuper = function(args, o) { return "" + (this.superReference(o)) + ".call(" + (this.superThis(o)) + (args.length ? ', ' : '') + args + ")"; }; Call.prototype.compileSplat = function(o, splatArgs) { var base, fun, idt, name, ref; if (this.isSuper) { return "" + (this.superReference(o)) + ".apply(" + (this.superThis(o)) + ", " + splatArgs + ")"; } if (this.isNew) { idt = this.tab + TAB; return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args), t = typeof result;\n" + idt + "return t == \"object\" || t == \"function\" ? result || child : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})"; } base = new Value(this.variable); if ((name = base.properties.pop()) && base.isComplex()) { ref = o.scope.freeVariable('ref'); fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o)); } else { fun = base.compile(o, LEVEL_ACCESS); if (SIMPLENUM.test(fun)) { fun = "(" + fun + ")"; } if (name) { ref = fun; fun += name.compile(o); } else { ref = 'null'; } } return "" + fun + ".apply(" + ref + ", " + splatArgs + ")"; }; return Call; })(Base); exports.Extends = Extends = (function(_super) { __extends(Extends, _super); function Extends(child, parent) { this.child = child; this.parent = parent; } Extends.prototype.children = ['child', 'parent']; Extends.prototype.compile = function(o) { return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o); }; return Extends; })(Base); exports.Access = Access = (function(_super) { __extends(Access, _super); function Access(name, tag) { this.name = name; this.name.asKey = true; this.soak = tag === 'soak'; } Access.prototype.children = ['name']; Access.prototype.compile = function(o) { var name; name = this.name.compile(o); if (IDENTIFIER.test(name)) { return "." + name; } else { return "[" + name + "]"; } }; Access.prototype.isComplex = NO; return Access; })(Base); exports.Index = Index = (function(_super) { __extends(Index, _super); function Index(index) { this.index = index; } Index.prototype.children = ['index']; Index.prototype.compile = function(o) { return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]"; }; Index.prototype.isComplex = function() { return this.index.isComplex(); }; return Index; })(Base); exports.Range = Range = (function(_super) { __extends(Range, _super); Range.prototype.children = ['from', 'to']; function Range(from, to, tag) { this.from = from; this.to = to; this.exclusive = tag === 'exclusive'; this.equals = this.exclusive ? '' : '='; } Range.prototype.compileVariables = function(o) { var step, _ref2, _ref3, _ref4, _ref5; o = merge(o, { top: true }); _ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1]; _ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1]; if (step = del(o, 'step')) { _ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1]; } _ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1]; if (this.stepVar) { return this.stepNum = this.stepVar.match(SIMPLENUM); } }; Range.prototype.compileNode = function(o) { var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3; if (!this.fromVar) { this.compileVariables(o); } if (!o.index) { return this.compileArray(o); } known = this.fromNum && this.toNum; idx = del(o, 'index'); idxName = del(o, 'name'); namedIndex = idxName && idxName !== idx; varPart = "" + idx + " = " + this.fromC; if (this.toC !== this.toVar) { varPart += ", " + this.toC; } if (this.step !== this.stepVar) { varPart += ", " + this.step; } _ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1]; condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar); stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--"; if (namedIndex) { varPart = "" + idxName + " = " + varPart; } if (namedIndex) { stepPart = "" + idxName + " = " + stepPart; } return "" + varPart + "; " + condPart + "; " + stepPart; }; Range.prototype.compileArray = function(o) { var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results; if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) { range = (function() { _results = []; for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); } return _results; }).apply(this); if (this.exclusive) { range.pop(); } return "[" + (range.join(', ')) + "]"; } idt = this.tab + TAB; i = o.scope.freeVariable('i'); result = o.scope.freeVariable('results'); pre = "\n" + idt + result + " = [];"; if (this.fromNum && this.toNum) { o.index = i; body = this.compileNode(o); } else { vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : ''); cond = "" + this.fromVar + " <= " + this.toVar; body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--"; } post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent; hasArgs = function(node) { return node != null ? node.contains(function(n) { return n instanceof Literal && n.value === 'arguments' && !n.asKey; }) : void 0; }; if (hasArgs(this.from) || hasArgs(this.to)) { args = ', arguments'; } return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")"; }; return Range; })(Base); exports.Slice = Slice = (function(_super) { __extends(Slice, _super); Slice.prototype.children = ['range']; function Slice(range) { this.range = range; Slice.__super__.constructor.call(this); } Slice.prototype.compileNode = function(o) { var compiled, from, fromStr, to, toStr, _ref2; _ref2 = this.range, to = _ref2.to, from = _ref2.from; fromStr = from && from.compile(o, LEVEL_PAREN) || '0'; compiled = to && to.compile(o, LEVEL_PAREN); if (to && !(!this.range.exclusive && +compiled === -1)) { toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "+" + compiled + " + 1 || 9e9")); } return ".slice(" + fromStr + (toStr || '') + ")"; }; return Slice; })(Base); exports.Obj = Obj = (function(_super) { __extends(Obj, _super); function Obj(props, generated) { this.generated = generated != null ? generated : false; this.objects = this.properties = props || []; } Obj.prototype.children = ['properties']; Obj.prototype.compileNode = function(o) { var i, idt, indent, join, lastNoncom, node, obj, prop, props, _i, _len; props = this.properties; if (!props.length) { return (this.front ? '({})' : '{}'); } if (this.generated) { for (_i = 0, _len = props.length; _i < _len; _i++) { node = props[_i]; if (node instanceof Value) { throw new Error('cannot have an implicit value in an implicit object'); } } } idt = o.indent += TAB; lastNoncom = this.lastNonComment(this.properties); props = (function() { var _j, _len1, _results; _results = []; for (i = _j = 0, _len1 = props.length; _j < _len1; i = ++_j) { prop = props[i]; join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n'; indent = prop instanceof Comment ? '' : idt; if (prop instanceof Value && prop["this"]) { prop = new Assign(prop.properties[0].name, prop, 'object'); } if (!(prop instanceof Comment)) { if (!(prop instanceof Assign)) { prop = new Assign(prop, prop, 'object'); } (prop.variable.base || prop.variable).asKey = true; } _results.push(indent + prop.compile(o, LEVEL_TOP) + join); } return _results; })(); props = props.join(''); obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}"; if (this.front) { return "(" + obj + ")"; } else { return obj; } }; Obj.prototype.assigns = function(name) { var prop, _i, _len, _ref2; _ref2 = this.properties; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { prop = _ref2[_i]; if (prop.assigns(name)) { return true; } } return false; }; return Obj; })(Base); exports.Arr = Arr = (function(_super) { __extends(Arr, _super); function Arr(objs) { this.objects = objs || []; } Arr.prototype.children = ['objects']; Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects; Arr.prototype.compileNode = function(o) { var code, obj, objs; if (!this.objects.length) { return '[]'; } o.indent += TAB; objs = this.filterImplicitObjects(this.objects); if (code = Splat.compileSplattedArray(o, objs)) { return code; } code = ((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = objs.length; _i < _len; _i++) { obj = objs[_i]; _results.push(obj.compile(o, LEVEL_LIST)); } return _results; })()).join(', '); if (code.indexOf('\n') >= 0) { return "[\n" + o.indent + code + "\n" + this.tab + "]"; } else { return "[" + code + "]"; } }; Arr.prototype.assigns = function(name) { var obj, _i, _len, _ref2; _ref2 = this.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; if (obj.assigns(name)) { return true; } } return false; }; return Arr; })(Base); exports.Class = Class = (function(_super) { __extends(Class, _super); function Class(variable, parent, body) { this.variable = variable; this.parent = parent; this.body = body != null ? body : new Block; this.boundFuncs = []; this.body.classBody = true; } Class.prototype.children = ['variable', 'parent', 'body']; Class.prototype.determineName = function() { var decl, tail; if (!this.variable) { return null; } decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value; if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) { throw SyntaxError("variable name may not be " + decl); } return decl && (decl = IDENTIFIER.test(decl) && decl); }; Class.prototype.setContext = function(name) { return this.body.traverseChildren(false, function(node) { if (node.classBody) { return false; } if (node instanceof Literal && node.value === 'this') { return node.value = name; } else if (node instanceof Code) { node.klass = name; if (node.bound) { return node.context = name; } } }); }; Class.prototype.addBoundFunctions = function(o) { var bvar, lhs, _i, _len, _ref2, _results; if (this.boundFuncs.length) { _ref2 = this.boundFuncs; _results = []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { bvar = _ref2[_i]; lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o); _results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)"))); } return _results; } }; Class.prototype.addProperties = function(node, name, o) { var assign, base, exprs, func, props; props = node.base.properties.slice(0); exprs = (function() { var _results; _results = []; while (assign = props.shift()) { if (assign instanceof Assign) { base = assign.variable.base; delete assign.context; func = assign.value; if (base.value === 'constructor') { if (this.ctor) { throw new Error('cannot define more than one constructor in a class'); } if (func.bound) { throw new Error('cannot define a constructor as a bound function'); } if (func instanceof Code) { assign = this.ctor = func; } else { this.externalCtor = o.scope.freeVariable('class'); assign = new Assign(new Literal(this.externalCtor), func); } } else { if (assign.variable["this"]) { func["static"] = true; if (func.bound) { func.context = name; } } else { assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]); if (func instanceof Code && func.bound) { this.boundFuncs.push(base); func.bound = false; } } } } _results.push(assign); } return _results; }).call(this); return compact(exprs); }; Class.prototype.walkBody = function(name, o) { var _this = this; return this.traverseChildren(false, function(child) { var exps, i, node, _i, _len, _ref2; if (child instanceof Class) { return false; } if (child instanceof Block) { _ref2 = exps = child.expressions; for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { node = _ref2[i]; if (node instanceof Value && node.isObject(true)) { exps[i] = _this.addProperties(node, name, o); } } return child.expressions = exps = flatten(exps); } }); }; Class.prototype.hoistDirectivePrologue = function() { var expressions, index, node; index = 0; expressions = this.body.expressions; while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) { ++index; } return this.directives = expressions.splice(0, index); }; Class.prototype.ensureConstructor = function(name) { if (!this.ctor) { this.ctor = new Code; if (this.parent) { this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)")); } if (this.externalCtor) { this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)")); } this.ctor.body.makeReturn(); this.body.expressions.unshift(this.ctor); } this.ctor.ctor = this.ctor.name = name; this.ctor.klass = null; return this.ctor.noReturn = true; }; Class.prototype.compileNode = function(o) { var call, decl, klass, lname, name, params, _ref2; decl = this.determineName(); name = decl || '_Class'; if (name.reserved) { name = "_" + name; } lname = new Literal(name); this.hoistDirectivePrologue(); this.setContext(name); this.walkBody(name, o); this.ensureConstructor(name); this.body.spaced = true; if (!(this.ctor instanceof Code)) { this.body.expressions.unshift(this.ctor); } this.body.expressions.push(lname); (_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives); this.addBoundFunctions(o); call = Closure.wrap(this.body); if (this.parent) { this.superClass = new Literal(o.scope.freeVariable('super', false)); this.body.expressions.unshift(new Extends(lname, this.superClass)); call.args.push(this.parent); params = call.variable.params || call.variable.base.params; params.push(new Param(this.superClass)); } klass = new Parens(call, true); if (this.variable) { klass = new Assign(this.variable, klass); } return klass.compile(o); }; return Class; })(Base); exports.Assign = Assign = (function(_super) { __extends(Assign, _super); function Assign(variable, value, context, options) { var forbidden, name, _ref2; this.variable = variable; this.value = value; this.context = context; this.param = options && options.param; this.subpattern = options && options.subpattern; forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0); if (forbidden && this.context !== 'object') { throw SyntaxError("variable name may not be \"" + name + "\""); } } Assign.prototype.children = ['variable', 'value']; Assign.prototype.isStatement = function(o) { return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0; }; Assign.prototype.assigns = function(name) { return this[this.context === 'object' ? 'value' : 'variable'].assigns(name); }; Assign.prototype.unfoldSoak = function(o) { return unfoldSoak(o, this, 'variable'); }; Assign.prototype.compileNode = function(o) { var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5; if (isValue = this.variable instanceof Value) { if (this.variable.isArray() || this.variable.isObject()) { return this.compilePatternMatch(o); } if (this.variable.isSplice()) { return this.compileSplice(o); } if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') { return this.compileConditional(o); } } name = this.variable.compile(o, LEVEL_LIST); if (!this.context) { if (!(varBase = this.variable.unwrapAll()).isAssignable()) { throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned."); } if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) { if (this.param) { o.scope.add(name, 'var'); } else { o.scope.find(name); } } } if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) { if (match[1]) { this.value.klass = match[1]; } this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5]; } val = this.value.compile(o, LEVEL_LIST); if (this.context === 'object') { return "" + name + ": " + val; } val = name + (" " + (this.context || '=') + " ") + val; if (o.level <= LEVEL_LIST) { return val; } else { return "(" + val + ")"; } }; Assign.prototype.compilePatternMatch = function(o) { var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; top = o.level === LEVEL_TOP; value = this.value; objects = this.variable.base.objects; if (!(olen = objects.length)) { code = value.compile(o); if (o.level >= LEVEL_OP) { return "(" + code + ")"; } else { return code; } } isObject = this.variable.isObject(); if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) { if (obj instanceof Assign) { _ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value; } else { if (obj.base instanceof Parens) { _ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1]; } else { idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0); } } acc = IDENTIFIER.test(idx.unwrap().value || 0); value = new Value(value); value.properties.push(new (acc ? Access : Index)(idx)); if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) { throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o))); } return new Assign(obj, value, null, { param: this.param }).compile(o, LEVEL_TOP); } vvar = value.compile(o, LEVEL_LIST); assigns = []; splat = false; if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) { assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar); vvar = ref; } for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) { obj = objects[i]; idx = i; if (isObject) { if (obj instanceof Assign) { _ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value; } else { if (obj.base instanceof Parens) { _ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1]; } else { idx = obj["this"] ? obj.properties[0].name : obj; } } } if (!splat && obj instanceof Splat) { name = obj.name.unwrap().value; obj = obj.unwrap(); val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i; if (rest = olen - i - 1) { ivar = o.scope.freeVariable('i'); val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])"; } else { val += ") : []"; } val = new Literal(val); splat = "" + ivar + "++"; } else { name = obj.unwrap().value; if (obj instanceof Splat) { obj = obj.name.compile(o); throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "..."); } if (typeof idx === 'number') { idx = new Literal(splat || idx); acc = false; } else { acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0); } val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]); } if ((name != null) && __indexOf.call(RESERVED, name) >= 0) { throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o))); } assigns.push(new Assign(obj, val, null, { param: this.param, subpattern: true }).compile(o, LEVEL_LIST)); } if (!(top || this.subpattern)) { assigns.push(vvar); } code = assigns.join(', '); if (o.level < LEVEL_LIST) { return code; } else { return "(" + code + ")"; } }; Assign.prototype.compileConditional = function(o) { var left, right, _ref2; _ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1]; if (!left.properties.length && left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) { throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined."); } if (__indexOf.call(this.context, "?") >= 0) { o.isExistentialEquals = true; } return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o); }; Assign.prototype.compileSplice = function(o) { var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4; _ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive; name = this.variable.compile(o); _ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1]; if (to) { if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) { to = +to.compile(o) - +fromRef; if (!exclusive) { to += 1; } } else { to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef; if (!exclusive) { to += ' + 1'; } } } else { to = "9e9"; } _ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1]; code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef; if (o.level > LEVEL_TOP) { return "(" + code + ")"; } else { return code; } }; return Assign; })(Base); exports.Code = Code = (function(_super) { __extends(Code, _super); function Code(params, body, tag) { this.params = params || []; this.body = body || new Block; this.bound = tag === 'boundfunc'; if (this.bound) { this.context = '_this'; } } Code.prototype.children = ['params', 'body']; Code.prototype.isStatement = function() { return !!this.ctor; }; Code.prototype.jumps = NO; Code.prototype.compileNode = function(o) { var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; o.scope = new Scope(o.scope, this.body, this); o.scope.shared = del(o, 'sharedScope'); o.indent += TAB; delete o.bare; delete o.isExistentialEquals; params = []; exprs = []; _ref2 = this.paramNames(); for (_i = 0, _len = _ref2.length; _i < _len; _i++) { name = _ref2[_i]; if (!o.scope.check(name)) { o.scope.parameter(name); } } _ref3 = this.params; for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { param = _ref3[_j]; if (!param.splat) { continue; } _ref4 = this.params; for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { p = _ref4[_k].name; if (p["this"]) { p = p.properties[0].name; } if (p.value) { o.scope.add(p.value, 'var', true); } } splats = new Assign(new Value(new Arr((function() { var _l, _len3, _ref5, _results; _ref5 = this.params; _results = []; for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { p = _ref5[_l]; _results.push(p.asReference(o)); } return _results; }).call(this))), new Value(new Literal('arguments'))); break; } _ref5 = this.params; for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { param = _ref5[_l]; if (param.isComplex()) { val = ref = param.asReference(o); if (param.value) { val = new Op('?', ref, param.value); } exprs.push(new Assign(new Value(param.name), val, '=', { param: true })); } else { ref = param; if (param.value) { lit = new Literal(ref.name.value + ' == null'); val = new Assign(new Value(param.name), param.value, '='); exprs.push(new If(lit, val)); } } if (!splats) { params.push(ref); } } wasEmpty = this.body.isEmpty(); if (splats) { exprs.unshift(splats); } if (exprs.length) { (_ref6 = this.body.expressions).unshift.apply(_ref6, exprs); } for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) { p = params[i]; o.scope.parameter(params[i] = p.compile(o)); } uniqs = []; _ref7 = this.paramNames(); for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) { name = _ref7[_n]; if (__indexOf.call(uniqs, name) >= 0) { throw SyntaxError("multiple parameters named '" + name + "'"); } uniqs.push(name); } if (!(wasEmpty || this.noReturn)) { this.body.makeReturn(); } if (this.bound) { if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) { this.bound = this.context = o.scope.parent.method.context; } else if (!this["static"]) { o.scope.parent.assign('_this', 'this'); } } idt = o.indent; code = 'function'; if (this.ctor) { code += ' ' + this.name; } code += '(' + params.join(', ') + ') {'; if (!this.body.isEmpty()) { code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab; } code += '}'; if (this.ctor) { return this.tab + code; } if (this.front || (o.level >= LEVEL_ACCESS)) { return "(" + code + ")"; } else { return code; } }; Code.prototype.paramNames = function() { var names, param, _i, _len, _ref2; names = []; _ref2 = this.params; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { param = _ref2[_i]; names.push.apply(names, param.names()); } return names; }; Code.prototype.traverseChildren = function(crossScope, func) { if (crossScope) { return Code.__super__.traverseChildren.call(this, crossScope, func); } }; return Code; })(Base); exports.Param = Param = (function(_super) { __extends(Param, _super); function Param(name, value, splat) { var _ref2; this.name = name; this.value = value; this.splat = splat; if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { throw SyntaxError("parameter name \"" + name + "\" is not allowed"); } } Param.prototype.children = ['name', 'value']; Param.prototype.compile = function(o) { return this.name.compile(o, LEVEL_LIST); }; Param.prototype.asReference = function(o) { var node; if (this.reference) { return this.reference; } node = this.name; if (node["this"]) { node = node.properties[0].name; if (node.value.reserved) { node = new Literal(o.scope.freeVariable(node.value)); } } else if (node.isComplex()) { node = new Literal(o.scope.freeVariable('arg')); } node = new Value(node); if (this.splat) { node = new Splat(node); } return this.reference = node; }; Param.prototype.isComplex = function() { return this.name.isComplex(); }; Param.prototype.names = function(name) { var atParam, names, obj, _i, _len, _ref2; if (name == null) { name = this.name; } atParam = function(obj) { var value; value = obj.properties[0].name.value; if (value.reserved) { return []; } else { return [value]; } }; if (name instanceof Literal) { return [name.value]; } if (name instanceof Value) { return atParam(name); } names = []; _ref2 = name.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; if (obj instanceof Assign) { names.push(obj.value.unwrap().value); } else if (obj instanceof Splat) { names.push(obj.name.unwrap().value); } else if (obj instanceof Value) { if (obj.isArray() || obj.isObject()) { names.push.apply(names, this.names(obj.base)); } else if (obj["this"]) { names.push.apply(names, atParam(obj)); } else { names.push(obj.base.value); } } else { throw SyntaxError("illegal parameter " + (obj.compile())); } } return names; }; return Param; })(Base); exports.Splat = Splat = (function(_super) { __extends(Splat, _super); Splat.prototype.children = ['name']; Splat.prototype.isAssignable = YES; function Splat(name) { this.name = name.compile ? name : new Literal(name); } Splat.prototype.assigns = function(name) { return this.name.assigns(name); }; Splat.prototype.compile = function(o) { if (this.index != null) { return this.compileParam(o); } else { return this.name.compile(o); } }; Splat.prototype.unwrap = function() { return this.name; }; Splat.compileSplattedArray = function(o, list, apply) { var args, base, code, i, index, node, _i, _len; index = -1; while ((node = list[++index]) && !(node instanceof Splat)) { continue; } if (index >= list.length) { return ''; } if (list.length === 1) { code = list[0].compile(o, LEVEL_LIST); if (apply) { return code; } return "" + (utility('slice')) + ".call(" + code + ")"; } args = list.slice(index); for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) { node = args[i]; code = node.compile(o, LEVEL_LIST); args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]"; } if (index === 0) { return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")"); } base = (function() { var _j, _len1, _ref2, _results; _ref2 = list.slice(0, index); _results = []; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { node = _ref2[_j]; _results.push(node.compile(o, LEVEL_LIST)); } return _results; })(); return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")"; }; return Splat; })(Base); exports.While = While = (function(_super) { __extends(While, _super); function While(condition, options) { this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition; this.guard = options != null ? options.guard : void 0; } While.prototype.children = ['condition', 'guard', 'body']; While.prototype.isStatement = YES; While.prototype.makeReturn = function(res) { if (res) { return While.__super__.makeReturn.apply(this, arguments); } else { this.returns = !this.jumps({ loop: true }); return this; } }; While.prototype.addBody = function(body) { this.body = body; return this; }; While.prototype.jumps = function() { var expressions, node, _i, _len; expressions = this.body.expressions; if (!expressions.length) { return false; } for (_i = 0, _len = expressions.length; _i < _len; _i++) { node = expressions[_i]; if (node.jumps({ loop: true })) { return node; } } return false; }; While.prototype.compileNode = function(o) { var body, code, rvar, set; o.indent += TAB; set = ''; body = this.body; if (body.isEmpty()) { body = ''; } else { if (this.returns) { body.makeReturn(rvar = o.scope.freeVariable('results')); set = "" + this.tab + rvar + " = [];\n"; } if (this.guard) { if (body.expressions.length > 1) { body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); } else { if (this.guard) { body = Block.wrap([new If(this.guard, body)]); } } } body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab; } code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}"); if (this.returns) { code += "\n" + this.tab + "return " + rvar + ";"; } return code; }; return While; })(Base); exports.Op = Op = (function(_super) { var CONVERSIONS, INVERSIONS; __extends(Op, _super); function Op(op, first, second, flip) { if (op === 'in') { return new In(first, second); } if (op === 'do') { return this.generateDo(first); } if (op === 'new') { if (first instanceof Call && !first["do"] && !first.isNew) { return first.newInstance(); } if (first instanceof Code && first.bound || first["do"]) { first = new Parens(first); } } this.operator = CONVERSIONS[op] || op; this.first = first; this.second = second; this.flip = !!flip; return this; } CONVERSIONS = { '==': '===', '!=': '!==', 'of': 'in' }; INVERSIONS = { '!==': '===', '===': '!==' }; Op.prototype.children = ['first', 'second']; Op.prototype.isSimpleNumber = NO; Op.prototype.isUnary = function() { return !this.second; }; Op.prototype.isComplex = function() { var _ref2; return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex(); }; Op.prototype.isChainable = function() { var _ref2; return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!=='; }; Op.prototype.invert = function() { var allInvertable, curr, fst, op, _ref2; if (this.isChainable() && this.first.isChainable()) { allInvertable = true; curr = this; while (curr && curr.operator) { allInvertable && (allInvertable = curr.operator in INVERSIONS); curr = curr.first; } if (!allInvertable) { return new Parens(this).invert(); } curr = this; while (curr && curr.operator) { curr.invert = !curr.invert; curr.operator = INVERSIONS[curr.operator]; curr = curr.first; } return this; } else if (op = INVERSIONS[this.operator]) { this.operator = op; if (this.first.unwrap() instanceof Op) { this.first.invert(); } return this; } else if (this.second) { return new Parens(this).invert(); } else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) { return fst; } else { return new Op('!', this); } }; Op.prototype.unfoldSoak = function(o) { var _ref2; return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first'); }; Op.prototype.generateDo = function(exp) { var call, func, param, passedParams, ref, _i, _len, _ref2; passedParams = []; func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp; _ref2 = func.params || []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { param = _ref2[_i]; if (param.value) { passedParams.push(param.value); delete param.value; } else { passedParams.push(param); } } call = new Call(exp, passedParams); call["do"] = true; return call; }; Op.prototype.compileNode = function(o) { var code, isChain, _ref2, _ref3; isChain = this.isChainable() && this.first.isChainable(); if (!isChain) { this.first.front = this.front; } if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) { throw SyntaxError('delete operand may not be argument or var'); } if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) { throw SyntaxError('prefix increment/decrement may not have eval or arguments operand'); } if (this.isUnary()) { return this.compileUnary(o); } if (isChain) { return this.compileChain(o); } if (this.operator === '?') { return this.compileExistence(o); } code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP); if (o.level <= LEVEL_OP) { return code; } else { return "(" + code + ")"; } }; Op.prototype.compileChain = function(o) { var code, fst, shared, _ref2; _ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1]; fst = this.first.compile(o, LEVEL_OP); code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP)); return "(" + code + ")"; }; Op.prototype.compileExistence = function(o) { var fst, ref; if (this.first.isComplex()) { ref = new Literal(o.scope.freeVariable('ref')); fst = new Parens(new Assign(ref, this.first)); } else { fst = this.first; ref = fst; } return new If(new Existence(fst), ref, { type: 'if' }).addElse(this.second).compile(o); }; Op.prototype.compileUnary = function(o) { var op, parts, plusMinus; if (o.level >= LEVEL_ACCESS) { return (new Parens(this)).compile(o); } parts = [op = this.operator]; plusMinus = op === '+' || op === '-'; if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) { parts.push(' '); } if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) { this.first = new Parens(this.first); } parts.push(this.first.compile(o, LEVEL_OP)); if (this.flip) { parts.reverse(); } return parts.join(''); }; Op.prototype.toString = function(idt) { return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator); }; return Op; })(Base); exports.In = In = (function(_super) { __extends(In, _super); function In(object, array) { this.object = object; this.array = array; } In.prototype.children = ['object', 'array']; In.prototype.invert = NEGATE; In.prototype.compileNode = function(o) { var hasSplat, obj, _i, _len, _ref2; if (this.array instanceof Value && this.array.isArray()) { _ref2 = this.array.base.objects; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { obj = _ref2[_i]; if (!(obj instanceof Splat)) { continue; } hasSplat = true; break; } if (!hasSplat) { return this.compileOrTest(o); } } return this.compileLoopTest(o); }; In.prototype.compileOrTest = function(o) { var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3; if (this.array.base.objects.length === 0) { return "" + (!!this.negated); } _ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1]; _ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1]; tests = (function() { var _i, _len, _ref4, _results; _ref4 = this.array.base.objects; _results = []; for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) { item = _ref4[i]; _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS)); } return _results; }).call(this); tests = tests.join(cnj); if (o.level < LEVEL_OP) { return tests; } else { return "(" + tests + ")"; } }; In.prototype.compileLoopTest = function(o) { var code, ref, sub, _ref2; _ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1]; code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0'); if (sub === ref) { return code; } code = sub + ', ' + code; if (o.level < LEVEL_LIST) { return code; } else { return "(" + code + ")"; } }; In.prototype.toString = function(idt) { return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : '')); }; return In; })(Base); exports.Try = Try = (function(_super) { __extends(Try, _super); function Try(attempt, error, recovery, ensure) { this.attempt = attempt; this.error = error; this.recovery = recovery; this.ensure = ensure; } Try.prototype.children = ['attempt', 'recovery', 'ensure']; Try.prototype.isStatement = YES; Try.prototype.jumps = function(o) { var _ref2; return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0); }; Try.prototype.makeReturn = function(res) { if (this.attempt) { this.attempt = this.attempt.makeReturn(res); } if (this.recovery) { this.recovery = this.recovery.makeReturn(res); } return this; }; Try.prototype.compileNode = function(o) { var catchPart, ensurePart, errorPart, tryPart; o.indent += TAB; errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' '; tryPart = this.attempt.compile(o, LEVEL_TOP); catchPart = (function() { var _ref2; if (this.recovery) { if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { throw SyntaxError("catch variable may not be \"" + this.error.value + "\""); } if (!o.scope.check(this.error.value)) { o.scope.add(this.error.value, 'param'); } return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"; } else if (!(this.ensure || this.recovery)) { return ' catch (_error) {}'; } }).call(this); ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : ''; return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart; }; return Try; })(Base); exports.Throw = Throw = (function(_super) { __extends(Throw, _super); function Throw(expression) { this.expression = expression; } Throw.prototype.children = ['expression']; Throw.prototype.isStatement = YES; Throw.prototype.jumps = NO; Throw.prototype.makeReturn = THIS; Throw.prototype.compileNode = function(o) { return this.tab + ("throw " + (this.expression.compile(o)) + ";"); }; return Throw; })(Base); exports.Existence = Existence = (function(_super) { __extends(Existence, _super); function Existence(expression) { this.expression = expression; } Existence.prototype.children = ['expression']; Existence.prototype.invert = NEGATE; Existence.prototype.compileNode = function(o) { var cmp, cnj, code, _ref2; this.expression.front = this.front; code = this.expression.compile(o, LEVEL_OP); if (IDENTIFIER.test(code) && !o.scope.check(code)) { _ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1]; code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null"; } else { code = "" + code + " " + (this.negated ? '==' : '!=') + " null"; } if (o.level <= LEVEL_COND) { return code; } else { return "(" + code + ")"; } }; return Existence; })(Base); exports.Parens = Parens = (function(_super) { __extends(Parens, _super); function Parens(body) { this.body = body; } Parens.prototype.children = ['body']; Parens.prototype.unwrap = function() { return this.body; }; Parens.prototype.isComplex = function() { return this.body.isComplex(); }; Parens.prototype.compileNode = function(o) { var bare, code, expr; expr = this.body.unwrap(); if (expr instanceof Value && expr.isAtomic()) { expr.front = this.front; return expr.compile(o); } code = expr.compile(o, LEVEL_PAREN); bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns)); if (bare) { return code; } else { return "(" + code + ")"; } }; return Parens; })(Base); exports.For = For = (function(_super) { __extends(For, _super); function For(body, source) { var _ref2; this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index; this.body = Block.wrap([body]); this.own = !!source.own; this.object = !!source.object; if (this.object) { _ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1]; } if (this.index instanceof Value) { throw SyntaxError('index cannot be a pattern matching expression'); } this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length; this.pattern = this.name instanceof Value; if (this.range && this.index) { throw SyntaxError('indexes do not apply to range loops'); } if (this.range && this.pattern) { throw SyntaxError('cannot pattern match over range loops'); } this.returns = false; } For.prototype.children = ['body', 'source', 'guard', 'step']; For.prototype.compileNode = function(o) { var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2; body = Block.wrap([this.body]); lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0; if (lastJumps && lastJumps instanceof Return) { this.returns = false; } source = this.range ? this.source.base : this.source; scope = o.scope; name = this.name && this.name.compile(o, LEVEL_LIST); index = this.index && this.index.compile(o, LEVEL_LIST); if (name && !this.pattern) { scope.find(name); } if (index) { scope.find(index); } if (this.returns) { rvar = scope.freeVariable('results'); } ivar = (this.object && index) || scope.freeVariable('i'); kvar = (this.range && name) || index || ivar; kvarAssign = kvar !== ivar ? "" + kvar + " = " : ""; if (this.step && !this.range) { stepvar = scope.freeVariable("step"); } if (this.pattern) { name = ivar; } varPart = ''; guardPart = ''; defPart = ''; idt1 = this.tab + TAB; if (this.range) { forPart = source.compile(merge(o, { index: ivar, name: name, step: this.step })); } else { svar = this.source.compile(o, LEVEL_LIST); if ((name || this.own) && !IDENTIFIER.test(svar)) { defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n"; svar = ref; } if (name && !this.pattern) { namePart = "" + name + " = " + svar + "[" + kvar + "]"; } if (!this.object) { lvar = scope.freeVariable('len'); forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length"; if (this.step) { forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)); } stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++")); forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart; } } if (this.returns) { resultPart = "" + this.tab + rvar + " = [];\n"; returnResult = "\n" + this.tab + "return " + rvar + ";"; body.makeReturn(rvar); } if (this.guard) { if (body.expressions.length > 1) { body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); } else { if (this.guard) { body = Block.wrap([new If(this.guard, body)]); } } } if (this.pattern) { body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]"))); } defPart += this.pluckDirectCall(o, body); if (namePart) { varPart = "\n" + idt1 + namePart + ";"; } if (this.object) { forPart = "" + kvar + " in " + svar; if (this.own) { guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;"; } } body = body.compile(merge(o, { indent: idt1 }), LEVEL_TOP); if (body) { body = '\n' + body + '\n'; } return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || ''); }; For.prototype.pluckDirectCall = function(o, body) { var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; defs = ''; _ref2 = body.expressions; for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) { expr = _ref2[idx]; expr = expr.unwrapAll(); if (!(expr instanceof Call)) { continue; } val = expr.variable.unwrapAll(); if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) { continue; } fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val; ref = new Literal(o.scope.freeVariable('fn')); base = new Value(ref); if (val.base) { _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1]; } body.expressions[idx] = new Call(base, expr.args); defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n'; } return defs; }; return For; })(While); exports.Switch = Switch = (function(_super) { __extends(Switch, _super); function Switch(subject, cases, otherwise) { this.subject = subject; this.cases = cases; this.otherwise = otherwise; } Switch.prototype.children = ['subject', 'cases', 'otherwise']; Switch.prototype.isStatement = YES; Switch.prototype.jumps = function(o) { var block, conds, _i, _len, _ref2, _ref3, _ref4; if (o == null) { o = { block: true }; } _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { _ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1]; if (block.jumps(o)) { return block; } } return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0; }; Switch.prototype.makeReturn = function(res) { var pair, _i, _len, _ref2, _ref3; _ref2 = this.cases; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { pair = _ref2[_i]; pair[1].makeReturn(res); } if (res) { this.otherwise || (this.otherwise = new Block([new Literal('void 0')])); } if ((_ref3 = this.otherwise) != null) { _ref3.makeReturn(res); } return this; }; Switch.prototype.compileNode = function(o) { var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5; idt1 = o.indent + TAB; idt2 = o.indent = idt1 + TAB; code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n"); _ref3 = this.cases; for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) { _ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1]; _ref5 = flatten([conditions]); for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) { cond = _ref5[_j]; if (!this.subject) { cond = cond.invert(); } code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n"); } if (body = block.compile(o, LEVEL_TOP)) { code += body + '\n'; } if (i === this.cases.length - 1 && !this.otherwise) { break; } expr = this.lastNonComment(block.expressions); if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) { continue; } code += idt2 + 'break;\n'; } if (this.otherwise && this.otherwise.expressions.length) { code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n"); } return code + this.tab + '}'; }; return Switch; })(Base); exports.If = If = (function(_super) { __extends(If, _super); function If(condition, body, options) { this.body = body; if (options == null) { options = {}; } this.condition = options.type === 'unless' ? condition.invert() : condition; this.elseBody = null; this.isChain = false; this.soak = options.soak; } If.prototype.children = ['condition', 'body', 'elseBody']; If.prototype.bodyNode = function() { var _ref2; return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0; }; If.prototype.elseBodyNode = function() { var _ref2; return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0; }; If.prototype.addElse = function(elseBody) { if (this.isChain) { this.elseBodyNode().addElse(elseBody); } else { this.isChain = elseBody instanceof If; this.elseBody = this.ensureBlock(elseBody); } return this; }; If.prototype.isStatement = function(o) { var _ref2; return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0); }; If.prototype.jumps = function(o) { var _ref2; return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0); }; If.prototype.compileNode = function(o) { if (this.isStatement(o)) { return this.compileStatement(o); } else { return this.compileExpression(o); } }; If.prototype.makeReturn = function(res) { if (res) { this.elseBody || (this.elseBody = new Block([new Literal('void 0')])); } this.body && (this.body = new Block([this.body.makeReturn(res)])); this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)])); return this; }; If.prototype.ensureBlock = function(node) { if (node instanceof Block) { return node; } else { return new Block([node]); } }; If.prototype.compileStatement = function(o) { var body, child, cond, exeq, ifPart; child = del(o, 'chainChild'); exeq = del(o, 'isExistentialEquals'); if (exeq) { return new If(this.condition.invert(), this.elseBodyNode(), { type: 'if' }).compile(o); } cond = this.condition.compile(o, LEVEL_PAREN); o.indent += TAB; body = this.ensureBlock(this.body); ifPart = "if (" + cond + ") {\n" + (body.compile(o)) + "\n" + this.tab + "}"; if (!child) { ifPart = this.tab + ifPart; } if (!this.elseBody) { return ifPart; } return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"); }; If.prototype.compileExpression = function(o) { var alt, body, code, cond; cond = this.condition.compile(o, LEVEL_COND); body = this.bodyNode().compile(o, LEVEL_LIST); alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0'; code = "" + cond + " ? " + body + " : " + alt; if (o.level >= LEVEL_COND) { return "(" + code + ")"; } else { return code; } }; If.prototype.unfoldSoak = function() { return this.soak && this; }; return If; })(Base); Closure = { wrap: function(expressions, statement, noReturn) { var args, call, func, mentionsArgs, meth; if (expressions.jumps()) { return expressions; } func = new Code([], Block.wrap([expressions])); args = []; if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) { meth = new Literal(mentionsArgs ? 'apply' : 'call'); args = [new Literal('this')]; if (mentionsArgs) { args.push(new Literal('arguments')); } func = new Value(func, [new Access(meth)]); } func.noReturn = noReturn; call = new Call(func, args); if (statement) { return Block.wrap([call]); } else { return call; } }, literalArgs: function(node) { return node instanceof Literal && node.value === 'arguments' && !node.asKey; }, literalThis: function(node) { return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound) || (node instanceof Call && node.isSuper); } }; unfoldSoak = function(o, parent, name) { var ifn; if (!(ifn = parent[name].unfoldSoak(o))) { return; } parent[name] = ifn.body; ifn.body = new Value(parent); return ifn; }; UTILITIES = { "extends": function() { return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }"; }, bind: function() { return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }'; }, indexOf: function() { return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }"; }, hasProp: function() { return '{}.hasOwnProperty'; }, slice: function() { return '[].slice'; } }; LEVEL_TOP = 1; LEVEL_PAREN = 2; LEVEL_LIST = 3; LEVEL_COND = 4; LEVEL_OP = 5; LEVEL_ACCESS = 6; TAB = ' '; IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$"); SIMPLENUM = /^[+-]?\d+$/; METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$"); IS_STRING = /^['"]/; utility = function(name) { var ref; ref = "__" + name; Scope.root.assign(ref, UTILITIES[name]()); return ref; }; multident = function(code, tab) { code = code.replace(/\n/g, '$&' + tab); return code.replace(/\s+$/, ''); }; }).call(this);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.4.4.2_A4.7; * @section: 15.4.4.2, 11.2.2; * @assertion: The toString property of Array can't be used as constructor; * @description: If property does not implement the internal [[Construct]] method, throw a TypeError exception; */ //CHECK#1 try { new Array.prototype.toString(); $ERROR('#1.1: new Array.prototype.toString() throw TypeError. Actual: ' + (new Array.prototype.toString())); } catch (e) { if ((e instanceof TypeError) !== true) { $ERROR('#1.2: new Array.prototype.toString() throw TypeError. Actual: ' + (e)); } }
/* * Planck.js v0.2.6 * * Copyright (c) 2016-2018 Ali Shakiba http://shakiba.me/planck.js * Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ !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){ exports.internal = {}; exports.Math = require("./common/Math"); exports.Vec2 = require("./common/Vec2"); exports.Vec3 = require("./common/Vec3"); exports.Mat22 = require("./common/Mat22"); exports.Mat33 = require("./common/Mat33"); exports.Transform = require("./common/Transform"); exports.Rot = require("./common/Rot"); exports.AABB = require("./collision/AABB"); exports.Shape = require("./Shape"); exports.Fixture = require("./Fixture"); exports.Body = require("./Body"); exports.Contact = require("./Contact"); exports.Joint = require("./Joint"); exports.World = require("./World"); exports.Circle = require("./shape/CircleShape"); exports.Edge = require("./shape/EdgeShape"); exports.Polygon = require("./shape/PolygonShape"); exports.Chain = require("./shape/ChainShape"); exports.Box = require("./shape/BoxShape"); require("./shape/CollideCircle"); require("./shape/CollideEdgeCircle"); exports.internal.CollidePolygons = require("./shape/CollidePolygon"); require("./shape/CollideCirclePolygone"); require("./shape/CollideEdgePolygon"); exports.DistanceJoint = require("./joint/DistanceJoint"); exports.FrictionJoint = require("./joint/FrictionJoint"); exports.GearJoint = require("./joint/GearJoint"); exports.MotorJoint = require("./joint/MotorJoint"); exports.MouseJoint = require("./joint/MouseJoint"); exports.PrismaticJoint = require("./joint/PrismaticJoint"); exports.PulleyJoint = require("./joint/PulleyJoint"); exports.RevoluteJoint = require("./joint/RevoluteJoint"); exports.RopeJoint = require("./joint/RopeJoint"); exports.WeldJoint = require("./joint/WeldJoint"); exports.WheelJoint = require("./joint/WheelJoint"); exports.internal.Sweep = require("./common/Sweep"); exports.internal.stats = require("./common/stats"); exports.internal.Manifold = require("./Manifold"); exports.internal.Distance = require("./collision/Distance"); exports.internal.TimeOfImpact = require("./collision/TimeOfImpact"); exports.internal.DynamicTree = require("./collision/DynamicTree"); exports.internal.Settings = require("./Settings"); },{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Mat22":16,"./common/Mat33":17,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Vec3":24,"./common/stats":26,"./joint/DistanceJoint":27,"./joint/FrictionJoint":28,"./joint/GearJoint":29,"./joint/MotorJoint":30,"./joint/MouseJoint":31,"./joint/PrismaticJoint":32,"./joint/PulleyJoint":33,"./joint/RevoluteJoint":34,"./joint/RopeJoint":35,"./joint/WeldJoint":36,"./joint/WheelJoint":37,"./shape/BoxShape":38,"./shape/ChainShape":39,"./shape/CircleShape":40,"./shape/CollideCircle":41,"./shape/CollideCirclePolygone":42,"./shape/CollideEdgeCircle":43,"./shape/CollideEdgePolygon":44,"./shape/CollidePolygon":45,"./shape/EdgeShape":46,"./shape/PolygonShape":47}],2:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Body; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var Rot = require("./common/Rot"); var Math = require("./common/Math"); var Sweep = require("./common/Sweep"); var Transform = require("./common/Transform"); var Velocity = require("./common/Velocity"); var Position = require("./common/Position"); var Fixture = require("./Fixture"); var Shape = require("./Shape"); var World = require("./World"); var staticBody = Body.STATIC = "static"; var kinematicBody = Body.KINEMATIC = "kinematic"; var dynamicBody = Body.DYNAMIC = "dynamic"; /** * @typedef {Object} BodyDef * * @prop type Body types are static, kinematic, or dynamic. Note: if a dynamic * body would have zero mass, the mass is set to one. * * @prop position The world position of the body. Avoid creating bodies at the * origin since this can lead to many overlapping shapes. * * @prop angle The world angle of the body in radians. * * @prop linearVelocity The linear velocity of the body's origin in world * co-ordinates. * * @prop linearDamping Linear damping is use to reduce the linear velocity. The * damping parameter can be larger than 1.0 but the damping effect becomes * sensitive to the time step when the damping parameter is large. * * @prop angularDamping Angular damping is use to reduce the angular velocity. * The damping parameter can be larger than 1.0 but the damping effect * becomes sensitive to the time step when the damping parameter is large. * * @prop fixedRotation Should this body be prevented from rotating? Useful for * characters. * * @prop bullet Is this a fast moving body that should be prevented from * tunneling through other moving bodies? Note that all bodies are * prevented from tunneling through kinematic and static bodies. This * setting is only considered on dynamic bodies. Warning: You should use * this flag sparingly since it increases processing time. * * @prop active Does this body start out active? * * @prop awake Is this body initially awake or sleeping? * * @prop allowSleep Set this flag to false if this body should never fall * asleep. Note that this increases CPU usage. */ 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 }; /** * @class * * A rigid body composed of one or more fixtures. * * @param {BodyDef} def */ 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; } // Rotational inertia about the center of mass. this.m_I = 0; this.m_invI = 0; // the body origin transform this.m_xf = Transform.identity(); this.m_xf.p = Vec2.clone(def.position); this.m_xf.q.setAngle(def.angle); // the swept motion for CCD this.m_sweep = new Sweep(); this.m_sweep.setTransform(this.m_xf); // position and velocity correction this.c_velocity = new Velocity(); this.c_position = new Position(); this.m_force = Vec2.zero(); this.m_torque = 0; this.m_linearVelocity = Vec2.clone(def.linearVelocity); this.m_angularVelocity = def.angularVelocity; this.m_linearDamping = def.linearDamping; this.m_angularDamping = def.angularDamping; this.m_gravityScale = def.gravityScale; this.m_sleepTime = 0; this.m_jointList = null; this.m_contactList = null; this.m_fixtureList = null; this.m_prev = null; this.m_next = null; this.m_destroyed = false; } Body.prototype.isWorldLocked = function() { return this.m_world && this.m_world.isLocked() ? true : false; }; Body.prototype.getWorld = function() { return this.m_world; }; Body.prototype.getNext = function() { return this.m_next; }; Body.prototype.setUserData = function(data) { this.m_userData = data; }; Body.prototype.getUserData = function() { return this.m_userData; }; Body.prototype.getFixtureList = function() { return this.m_fixtureList; }; Body.prototype.getJointList = function() { return this.m_jointList; }; /** * Warning: this list changes during the time step and you may miss some * collisions if you don't use ContactListener. */ 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; }; /** * This will alter the mass and velocity. */ 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; }; /** * @private */ Body.prototype.getType = function() { return this.m_type; }; /** * * @private */ 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; // Delete the attached contacts. var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; // Touch the proxies so that new contacts will be created (when appropriate) 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; }; /** * Should this body be treated like a bullet for continuous collision detection? */ 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; }; /** * Set the sleep state of the body. A sleeping body has very low CPU cost. * * @param flag Set to true to wake the body, false to put it to sleep. */ 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; }; /** * Set the active state of the body. An inactive body is not simulated and * cannot be collided with or woken up. If you pass a flag of true, all fixtures * will be added to the broad-phase. If you pass a flag of false, all fixtures * will be removed from the broad-phase and all contacts will be destroyed. * Fixtures and joints are otherwise unaffected. * * You may continue to create/destroy fixtures and joints on inactive bodies. * Fixtures on an inactive body are implicitly inactive and will not participate * in collisions, ray-casts, or queries. Joints connected to an inactive body * are implicitly inactive. An inactive body is still owned by a World object * and remains */ 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) { // Create all proxies. 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 { // Destroy all proxies. var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.destroyProxies(broadPhase); } // Destroy the attached contacts. 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; }; /** * Set this body to have fixed rotation. This causes the mass to be reset. */ Body.prototype.setFixedRotation = function(flag) { if (this.m_fixedRotationFlag == flag) { return; } this.m_fixedRotationFlag = !!flag; this.m_angularVelocity = 0; this.resetMassData(); }; /** * Get the world transform for the body's origin. */ Body.prototype.getTransform = function() { return this.m_xf; }; /** * Set the position of the body's origin and rotation. Manipulating a body's * transform may cause non-physical behavior. Note: contacts are updated on the * next call to World.step. * * @param position The world position of the body's local origin. * @param angle The world rotation in radians. */ 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); }; /** * Update fixtures in broad-phase. */ 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); } }; /** * Used in TOI. */ Body.prototype.advance = function(alpha) { // Advance to the new safe time. This doesn't sync the broad-phase. 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); }; /** * Get the world position for the body's origin. */ Body.prototype.getPosition = function() { return this.m_xf.p; }; Body.prototype.setPosition = function(p) { this.setTransform(p, this.m_sweep.a); }; /** * Get the current world rotation angle in radians. */ Body.prototype.getAngle = function() { return this.m_sweep.a; }; Body.prototype.setAngle = function(angle) { this.setTransform(this.m_xf.p, angle); }; /** * Get the world position of the center of mass. */ Body.prototype.getWorldCenter = function() { return this.m_sweep.c; }; /** * Get the local position of the center of mass. */ Body.prototype.getLocalCenter = function() { return this.m_sweep.localCenter; }; /** * Get the linear velocity of the center of mass. * * @return the linear velocity of the center of mass. */ Body.prototype.getLinearVelocity = function() { return this.m_linearVelocity; }; /** * Get the world linear velocity of a world point attached to this body. * * @param worldPoint A point in world coordinates. */ 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)); }; /** * Get the world velocity of a local point. * * @param localPoint A point in local coordinates. */ Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) { return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint)); }; /** * Set the linear velocity of the center of mass. * * @param v The new linear velocity of the center of mass. */ 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); }; /** * Get the angular velocity. * * @returns the angular velocity in radians/second. */ Body.prototype.getAngularVelocity = function() { return this.m_angularVelocity; }; /** * Set the angular velocity. * * @param omega The new angular velocity in radians/second. */ 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; }; /** * Scale the gravity applied to this body. */ Body.prototype.setGravityScale = function(scale) { this.m_gravityScale = scale; }; /** * Get the total mass of the body. * * @returns The mass, usually in kilograms (kg). */ Body.prototype.getMass = function() { return this.m_mass; }; /** * Get the rotational inertia of the body about the local origin. * * @return the rotational inertia, usually in kg-m^2. */ Body.prototype.getInertia = function() { return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter); }; /** * @typedef {Object} MassData This holds the mass data computed for a shape. * * @prop mass The mass of the shape, usually in kilograms. * @prop center The position of the shape's centroid relative to the shape's * origin. * @prop I The rotational inertia of the shape about the local origin. */ function MassData() { this.mass = 0; this.center = Vec2.zero(); this.I = 0; } /** * Copy the mass data of the body to data. */ Body.prototype.getMassData = function(data) { data.mass = this.m_mass; data.I = this.getInertia(); data.center.set(this.m_sweep.localCenter); }; /** * This resets the mass properties to the sum of the mass properties of the * fixtures. This normally does not need to be called unless you called * SetMassData to override the mass and you later want to reset the mass. */ Body.prototype.resetMassData = function() { // Compute mass data from shapes. Each shape has its own density. this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.setZero(); // Static and kinematic bodies have zero mass. 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()); // Accumulate mass over all fixtures. var localCenter = Vec2.zero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density == 0) { continue; } var massData = new MassData(); f.getMassData(massData); this.m_mass += massData.mass; localCenter.addMul(massData.mass, massData.center); this.m_I += massData.I; } // Compute center of mass. if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.mul(this.m_invMass); } else { // Force all dynamic bodies to have a positive mass. this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && this.m_fixedRotationFlag == false) { // Center the inertia about the center of mass. 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; } // Move center of mass. var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(localCenter, this.m_xf); // Update center of mass velocity. this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; /** * Set the mass properties to override the mass properties of the fixtures. Note * that this changes the center of mass position. Note that creating or * destroying fixtures can also alter the mass. This function has no effect if * the body isn't dynamic. * * @param massData The mass properties. */ 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; } // Move center of mass. var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(massData.center, this.m_xf); // Update center of mass velocity. this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; /** * Apply a force at a world point. If the force is not applied at the center of * mass, it will generate a torque and affect the angular velocity. This wakes * up the body. * * @param force The world force vector, usually in Newtons (N). * @param point The world position of the point of application. * @param wake Also wake up the body */ Body.prototype.applyForce = function(force, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } // Don't accumulate a force if the body is sleeping. if (this.m_awakeFlag) { this.m_force.add(force); this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force); } }; /** * Apply a force to the center of mass. This wakes up the body. * * @param force The world force vector, usually in Newtons (N). * @param wake Also wake up the body */ Body.prototype.applyForceToCenter = function(force, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } // Don't accumulate a force if the body is sleeping if (this.m_awakeFlag) { this.m_force.add(force); } }; /** * Apply a torque. This affects the angular velocity without affecting the * linear velocity of the center of mass. This wakes up the body. * * @param torque About the z-axis (out of the screen), usually in N-m. * @param wake Also wake up the body */ Body.prototype.applyTorque = function(torque, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } // Don't accumulate a force if the body is sleeping if (this.m_awakeFlag) { this.m_torque += torque; } }; /** * Apply an impulse at a point. This immediately modifies the velocity. It also * modifies the angular velocity if the point of application is not at the * center of mass. This wakes up the body. * * @param impulse The world impulse vector, usually in N-seconds or kg-m/s. * @param point The world position of the point of application. * @param wake Also wake up the body */ Body.prototype.applyLinearImpulse = function(impulse, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } // Don't accumulate velocity if the body is sleeping if (this.m_awakeFlag) { this.m_linearVelocity.addMul(this.m_invMass, impulse); this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse); } }; /** * Apply an angular impulse. * * @param impulse The angular impulse in units of kg*m*m/s * @param wake Also wake up the body */ Body.prototype.applyAngularImpulse = function(impulse, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } // Don't accumulate velocity if the body is sleeping if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } }; /** * This is used to prevent connected bodies (by joints) from colliding, * depending on the joint's collideConnected flag. */ Body.prototype.shouldCollide = function(that) { // At least one body should be dynamic. if (this.m_type != dynamicBody && that.m_type != dynamicBody) { return false; } // Does a joint prevent collision? for (var jn = this.m_jointList; jn; jn = jn.next) { if (jn.other == that) { if (jn.joint.m_collideConnected == false) { return false; } } } return true; }; /** * Creates a fixture and attach it to this body. * * If the density is non-zero, this function automatically updates the mass of * the body. * * Contacts are not created until the next time step. * * Warning: This function is locked during callbacks. * @param {Shape|FixtureDef} shape Shape or fixture definition. * @param {FixtureDef|number} fixdef Fixture definition or just density. */ 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; // Adjust mass properties if needed. if (fixture.m_density > 0) { this.resetMassData(); } // Let the world know we have a new fixture. This will cause new contacts // to be created at the beginning of the next time step. this.m_world.m_newFixture = true; return fixture; }; /** * Destroy a fixture. This removes the fixture from the broad-phase and destroys * all contacts associated with this fixture. This will automatically adjust the * mass of the body if the body is dynamic and the fixture has positive density. * All fixtures attached to a body are implicitly destroyed when the body is * destroyed. * * Warning: This function is locked during callbacks. * * @param fixture The fixture to be removed. */ Body.prototype.destroyFixture = function(fixture) { _ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } _ASSERT && common.assert(fixture.m_body == this); // Remove the fixture from this body's singly linked list. var found = false; if (this.m_fixtureList === fixture) { this.m_fixtureList = fixture.m_next; found = true; } else { var node = this.m_fixtureList; while (node != null) { if (node.m_next === fixture) { node.m_next = fixture.m_next; found = true; break; } node = node.m_next; } } // You tried to remove a shape that is not attached to this body. _ASSERT && common.assert(found); // Destroy any contacts associated with the fixture. 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 destroys the contact and removes it from // this body's contact list. 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); // Reset the mass data. this.resetMassData(); }; /** * Get the corresponding world point of a local point. */ Body.prototype.getWorldPoint = function(localPoint) { return Transform.mulVec2(this.m_xf, localPoint); }; /** * Get the corresponding world vector of a local vector. */ Body.prototype.getWorldVector = function(localVector) { return Rot.mulVec2(this.m_xf.q, localVector); }; /** * Gets the corresponding local point of a world point. */ Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulTVec2(this.m_xf, worldPoint); }; /** * * Gets the corresponding local vector of a world vector. */ Body.prototype.getLocalVector = function(worldVector) { return Rot.mulTVec2(this.m_xf.q, worldVector); }; },{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":50,"./util/options":52}],3:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); var 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; /** * A contact edge is used to connect bodies and contacts together in a contact * graph where each body is a node and each contact is an edge. A contact edge * belongs to a doubly linked list maintained in each attached body. Each * contact has two contact nodes, one for each attached body. * * @prop {Contact} contact The contact * @prop {ContactEdge} prev The previous contact edge in the body's contact list * @prop {ContactEdge} next The next contact edge in the body's contact list * @prop {Body} other Provides quick access to the other body attached. */ function ContactEdge(contact) { this.contact = contact; this.prev; this.next; this.other; } /** * @function Contact~evaluate * * @param manifold * @param xfA * @param fixtureA * @param indexA * @param xfB * @param fixtureB * @param indexB */ /** * The class manages contact between two shapes. A contact exists for each * overlapping AABB in the broad-phase (except if filtered). Therefore a contact * object may exist that has no contact points. * * @param {Fixture} fA * @param {int} indexA * @param {Fixture} fB * @param {int} indexB * @param {Contact~evaluate} evaluateFcn */ function Contact(fA, indexA, fB, indexB, evaluateFcn) { // Nodes for connecting bodies. 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 contact has a valid TOI in m_toi 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 contact can be disabled (by user) this.m_enabledFlag = true; // Used when crawling contact graph when forming islands. this.m_islandFlag = false; // Set when the shapes are touching. this.m_touchingFlag = false; // This contact needs filtering because a fixture filter was changed. this.m_filterFlag = false; // This bullet contact had a TOI event this.m_bulletHitFlag = false; this.v_points = []; // VelocityConstraintPoint[maxManifoldPoints] 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 = []; // Vec2[maxManifoldPoints]; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); this.p_type; // Manifold.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; 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]; // ManifoldPoint 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); } }; /** * Get the contact manifold. Do not modify the manifold unless you understand * the internals of the library. */ Contact.prototype.getManifold = function() { return this.m_manifold; }; /** * Get the world manifold. * * @param {WorldManifold} [worldManifold] */ 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); }; /** * Enable/disable this contact. This can be used inside the pre-solve contact * listener. The contact is only disabled for the current time step (or sub-step * in continuous collisions). */ Contact.prototype.setEnabled = function(flag) { this.m_enabledFlag = !!flag; }; /** * Has this contact been disabled? */ Contact.prototype.isEnabled = function() { return this.m_enabledFlag; }; /** * Is this contact touching? */ Contact.prototype.isTouching = function() { return this.m_touchingFlag; }; /** * Get the next contact in the world's contact list. */ Contact.prototype.getNext = function() { return this.m_next; }; /** * Get fixture A in this contact. */ Contact.prototype.getFixtureA = function() { return this.m_fixtureA; }; /** * Get fixture B in this contact. */ Contact.prototype.getFixtureB = function() { return this.m_fixtureB; }; /** * Get the child primitive index for fixture A. */ Contact.prototype.getChildIndexA = function() { return this.m_indexA; }; /** * Get the child primitive index for fixture B. */ Contact.prototype.getChildIndexB = function() { return this.m_indexB; }; /** * Flag this contact for filtering. Filtering will occur the next time step. */ Contact.prototype.flagForFiltering = function() { this.m_filterFlag = true; }; /** * Override the default friction mixture. You can call this in * ContactListener.preSolve. This value persists until set or reset. */ Contact.prototype.setFriction = function(friction) { this.m_friction = friction; }; /** * Get the friction. */ Contact.prototype.getFriction = function() { return this.m_friction; }; /** * Reset the friction mixture to the default value. */ Contact.prototype.resetFriction = function() { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; /** * Override the default restitution mixture. You can call this in * ContactListener.preSolve. The value persists until you set or reset. */ Contact.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; /** * Get the restitution. */ Contact.prototype.getRestitution = function() { return this.m_restitution; }; /** * Reset the restitution to the default value. */ Contact.prototype.resetRestitution = function() { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; /** * Set the desired tangent speed for a conveyor belt behavior. In meters per * second. */ Contact.prototype.setTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; /** * Get the desired tangent speed. In meters per second. */ Contact.prototype.getTangentSpeed = function() { return this.m_tangentSpeed; }; /** * Called by Update method, and implemented by subclasses. */ 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); }; /** * Updates the contact manifold and touching status. * * Note: do not assume the fixture AABBs are overlapping or are valid. * * @param {function} listener.beginContact * @param {function} listener.endContact * @param {function} listener.preSolve */ Contact.prototype.update = function(listener) { // Re-enable this contact. 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(); // Is this contact a sensor? 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); // Sensors don't generate manifolds. this.m_manifold.pointCount = 0; } else { // TODO reuse manifold var oldManifold = this.m_manifold; this.m_manifold = new Manifold(); this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. 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) { // ContactID.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; // Solve normal constraints 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.mulVec2(xfA.q, localCenterA)); xfB.p = Vec2.sub(cB, Rot.mulVec2(xfB.q, localCenterB)); // PositionSolverManifold var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mulVec2(xfA, this.p_localPoint); var pointB = Transform.mulVec2(xfB, this.p_localPoints[0]); normal = Vec2.sub(pointB, pointA); normal.normalize(); point = Vec2.combine(.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.mulVec2(xfA.q, this.p_localNormal); var planePoint = Transform.mulVec2(xfA, this.p_localPoint); var clipPoint = Transform.mulVec2(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.mulVec2(xfB.q, this.p_localNormal); var planePoint = Transform.mulVec2(xfB, this.p_localPoint); var clipPoint = Transform.mulVec2(xfA, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; // Ensure normal points from A to B normal.mul(-1); break; } var rA = Vec2.sub(point, cA); var rB = Vec2.sub(point, cB); // Track max constraint error. minSeparation = Math.min(minSeparation, separation); var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; // Prevent large corrections and allow slop. var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0); // Compute the effective mass. var rnA = Vec2.cross(rA, normal); var rnB = Vec2.cross(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; // Compute normal impulse var impulse = K > 0 ? -C / K : 0; var P = Vec2.mul(impulse, normal); cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } positionA.c.set(cA); positionA.a = aA; positionB.c.set(cB); positionB.a = aB; return minSeparation; }; // TODO merge with ManifoldPoint 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.setCombine(1, cA, -1, Rot.mulVec2(xfA.q, localCenterA)); xfB.p.setCombine(1, cB, -1, Rot.mulVec2(xfB.q, localCenterB)); var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; // VelocityConstraintPoint vcp.rA.set(Vec2.sub(worldManifold.points[j], cA)); vcp.rB.set(Vec2.sub(worldManifold.points[j], cB)); 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; // Setup a velocity bias for restitution. 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 we have two points, then prepare the block solver. if (this.v_pointCount == 2 && step.blockSolve) { var vcp1 = this.v_points[0]; // VelocityConstraintPoint var vcp2 = this.v_points[1]; // VelocityConstraintPoint 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; // Ensure a reasonable condition number. var k_maxConditionNumber = 1e3; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { // K is safe to invert. this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { // The constraints are redundant, just use one. // TODO_ERIN use deepest? 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]; // VelocityConstraintPoint var P = Vec2.combine(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); wA -= iA * Vec2.cross(vcp.rA, P); vA.subMul(mA, P); wB += iB * Vec2.cross(vcp.rB, P); vB.addMul(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.storeConstraintImpulses = function(step) { var manifold = this.m_manifold; for (var j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } }; 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); // Solve tangent constraints first because non-penetration is more important // than friction. for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; // VelocityConstraintPoint // Relative velocity at contact var dv = Vec2.zero(); dv.addCombine(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.subCombine(1, vA, 1, Vec2.cross(wA, vcp.rA)); // Compute tangent force var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; var lambda = vcp.tangentMass * -vt; // Clamp the accumulated force var maxFriction = friction * vcp.normalImpulse; var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; // Apply contact impulse var P = Vec2.mul(lambda, tangent); vA.subMul(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } // Solve normal constraints if (this.v_pointCount == 1 || step.blockSolve == false) { for (var i = 0; i < this.v_pointCount; ++i) { var vcp = this.v_points[i]; // VelocityConstraintPoint // Relative velocity at contact var dv = Vec2.zero(); dv.addCombine(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.subCombine(1, vA, 1, Vec2.cross(wA, vcp.rA)); // Compute normal impulse var vn = Vec2.dot(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); // Clamp the accumulated impulse var newImpulse = Math.max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; // Apply contact impulse var P = Vec2.mul(lambda, normal); vA.subMul(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } } else { // Block solver developed in collaboration with Dirk Gregorius (back in // 01/07 on Box2D_Lite). // Build the mini LCP for this contact patch // // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = // 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) // b = vn0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). // The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. // So for the 2D contact problem the cases // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and // vn1 = 0 need to be tested. The first valid // solution that satisfies the problem is chosen. // // In order to account of the accumulated impulse 'a' (because of the // iterative nature of the solver which only requires // that the accumulated impulse is clamped and not the incremental // impulse) we change the impulse variable (x_i). // // Substitute: // // x = a + d // // a := old total impulse // x := new total impulse // d := incremental impulse // // For the current iteration we extend the formula for the incremental // impulse // to compute the new total impulse: // // vn = A * d + b // = A * (x - a) + b // = A * x + b - A * a // = A * x + b' // b' = b - A * a; var vcp1 = this.v_points[0]; // VelocityConstraintPoint var vcp2 = this.v_points[1]; // VelocityConstraintPoint var a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse); _ASSERT && common.assert(a.x >= 0 && a.y >= 0); // Relative velocity at contact 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)); // Compute normal velocity var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); // Compute b' b.sub(Mat22.mulVec2(this.v_K, a)); var k_errorTol = .001; // NOT_USED(k_errorTol); for (;;) { // // Case 1: vn = 0 // // 0 = A * x + b' // // Solve for x: // // x = - inv(A) * b' // var x = Mat22.mulVec2(this.v_normalMass, b).neg(); if (x.x >= 0 && x.y >= 0) { // Get the incremental impulse var d = Vec2.sub(x, a); // Apply incremental impulse var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { // Postconditions 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); // Compute normal velocity 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; } // // Case 2: vn1 = 0 and x2 = 0 // // 0 = a11 * x1 + a12 * 0 + b1' // vn2 = a21 * x1 + a22 * 0 + b2' // 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) { // Get the incremental impulse var d = Vec2.sub(x, a); // Apply incremental impulse var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { // Postconditions 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); // Compute normal velocity vn1 = Vec2.dot(dv1, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } // // Case 3: vn2 = 0 and x1 = 0 // // vn1 = a11 * 0 + a12 * x2 + b1' // 0 = a21 * 0 + a22 * x2 + b2' // 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) { // Resubstitute for the incremental impulse var d = Vec2.sub(x, a); // Apply incremental impulse var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { // Postconditions 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); // Compute normal velocity vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } // // Case 4: x1 = 0 and x2 = 0 // // vn1 = b1 // vn2 = b2; // x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { // Resubstitute for the incremental impulse var d = Vec2.sub(x, a); // Apply incremental impulse var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } // No solution, give up. This is hit sometimes, but it doesn't seem to // matter. break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; /** * Friction mixing law. The idea is to allow either fixture to drive the * restitution to zero. For example, anything slides on ice. */ function mixFriction(friction1, friction2) { return Math.sqrt(friction1 * friction2); } /** * Restitution mixing law. The idea is allow for anything to bounce off an * inelastic surface. For example, a superball bounces on anything. */ function mixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var s_registers = []; /** * @param fn function(fixtureA, indexA, fixtureB, indexB) Contact */ Contact.addType = function(type1, type2, callback) { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; }; Contact.create = function(fixtureA, indexA, fixtureB, indexB) { var typeA = fixtureA.getType(); // Shape.Type var typeB = fixtureB.getType(); // Shape.Type // TODO: pool contacts 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; } // Contact creation may swap fixtures. fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); // Connect to body A 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; // Connect to body B 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; // Wake up the bodies 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); } // Remove from body 1 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; } // Remove from body 2 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(); // Shape.Type var typeB = fixtureB.getType(); // Shape.Type 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":50}],4:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var AABB = require("./collision/AABB"); /** * @typedef {Object} FixtureDef * * A fixture definition is used to create a fixture. This class defines an * abstract fixture definition. You can reuse fixture definitions safely. * * @prop friction The friction coefficient, usually in the range [0,1] * @prop restitution The restitution (elasticity) usually in the range [0,1] * @prop density The density, usually in kg/m^2 * @prop isSensor A sensor shape collects contact information but never * generates a collision response * @prop userData * @prop filterGroupIndex Zero, positive or negative collision group. Fixtures with same positive groupIndex always collide and fixtures with same * negative groupIndex never collide. * @prop filterCategoryBits Collision category bit or bits that this fixture belongs * to. If groupIndex is zero or not matching, then at least one bit in this fixture * categoryBits should match other fixture maskBits and vice versa. * @prop filterMaskBits Collision category bit or bits that this fixture accept for * collision. */ var FixtureDef = { userData: null, friction: .2, restitution: 0, density: 0, isSensor: false, filterGroupIndex: 0, filterCategoryBits: 1, filterMaskBits: 65535 }; /** * This proxy is used internally to connect shape children to the broad-phase. */ function FixtureProxy(fixture, childIndex) { this.aabb = new AABB(); this.fixture = fixture; this.childIndex = childIndex; this.proxyId; } /** * A fixture is used to attach a shape to a body for collision detection. A * fixture inherits its transform from its parent. Fixtures hold additional * non-geometric data such as friction, collision filters, etc. Fixtures are * created via Body.createFixture. * * @param {Shape|FixtureDef} shape Shape of fixture definition. * @param {FixtureDef|number} def Fixture definition or number. */ 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; // TODO validate shape this.m_shape = shape; //.clone(); 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; } /** * Get the type of the child shape. You can use this to down cast to the * concrete shape. */ Fixture.prototype.getType = function() { return this.m_shape.getType(); }; /** * Get the child shape. You can modify the child shape, however you should not * change the number of vertices because this will crash some collision caching * mechanisms. Manipulating the shape may lead to non-physical behavior. */ Fixture.prototype.getShape = function() { return this.m_shape; }; /** * A sensor shape collects contact information but never generates a collision * response. */ Fixture.prototype.isSensor = function() { return this.m_isSensor; }; /** * Set if this fixture is a sensor. */ Fixture.prototype.setSensor = function(sensor) { if (sensor != this.m_isSensor) { this.m_body.setAwake(true); this.m_isSensor = sensor; } }; /** * Get the contact filtering data. */ // Fixture.prototype.getFilterData = function() { // return this.m_filter; // } /** * Get the user data that was assigned in the fixture definition. Use this to * store your application specific data. */ Fixture.prototype.getUserData = function() { return this.m_userData; }; /** * Set the user data. Use this to store your application specific data. */ Fixture.prototype.setUserData = function(data) { this.m_userData = data; }; /** * Get the parent body of this fixture. This is null if the fixture is not * attached. */ Fixture.prototype.getBody = function() { return this.m_body; }; /** * Get the next fixture in the parent body's fixture list. */ Fixture.prototype.getNext = function() { return this.m_next; }; /** * Get the density of this fixture. */ Fixture.prototype.getDensity = function() { return this.m_density; }; /** * Set the density of this fixture. This will _not_ automatically adjust the * mass of the body. You must call Body.resetMassData to update the body's mass. */ Fixture.prototype.setDensity = function(density) { _ASSERT && common.assert(Math.isFinite(density) && density >= 0); this.m_density = density; }; /** * Get the coefficient of friction, usually in the range [0,1]. */ Fixture.prototype.getFriction = function() { return this.m_friction; }; /** * Set the coefficient of friction. This will not change the friction of * existing contacts. */ Fixture.prototype.setFriction = function(friction) { this.m_friction = friction; }; /** * Get the coefficient of restitution. */ Fixture.prototype.getRestitution = function() { return this.m_restitution; }; /** * Set the coefficient of restitution. This will not change the restitution of * existing contacts. */ Fixture.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; /** * Test a point in world coordinates for containment in this fixture. */ Fixture.prototype.testPoint = function(p) { return this.m_shape.testPoint(this.m_body.getTransform(), p); }; /** * Cast a ray against this shape. */ Fixture.prototype.rayCast = function(output, input, childIndex) { return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex); }; /** * Get the mass data for this fixture. The mass data is based on the density and * the shape. The rotational inertia is about the shape's origin. This operation * may be expensive. */ Fixture.prototype.getMassData = function(massData) { this.m_shape.computeMass(massData, this.m_density); }; /** * Get the fixture's AABB. This AABB may be enlarge and/or stale. If you need a * more accurate AABB, compute it using the shape and the body transform. */ Fixture.prototype.getAABB = function(childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount); return this.m_proxies[childIndex].aabb; }; /** * These support body activation/deactivation. */ Fixture.prototype.createProxies = function(broadPhase, xf) { _ASSERT && common.assert(this.m_proxyCount == 0); // Create proxies in the broad-phase. 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) { // Destroy proxies in the broad-phase. 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; }; /** * Updates this fixture proxy in broad-phase (with combined AABB of current and * next transformation). */ Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; // Compute an AABB that covers the swept shape (may miss some rotation // effect). 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); } }; /** * Set the contact filtering data. This will not update contacts until the next * time step when either parent body is active and awake. This automatically * calls refilter. */ 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; }; /** * Call this if you want to establish collision that was previously disabled by * ContactFilter. */ Fixture.prototype.refilter = function() { if (this.m_body == null) { return; } // Flag associated contacts for filtering. 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; } // Touch each proxy so that new pairs may be created var broadPhase = world.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { broadPhase.touchProxy(this.m_proxies[i].proxyId); } }; /** * Implement this method to provide collision filtering, if you want finer * control over contact creation. * * Return true if contact calculations should be performed between these two * fixtures. * * Warning: for performance reasons this is only called when the AABBs begin to * overlap. * * @param {Fixture} fixtureA * @param {Fixture} fixtureB */ Fixture.prototype.shouldCollide = function(that) { if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) { return that.m_filterGroupIndex > 0; } var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0; return collide; }; },{"./collision/AABB":11,"./common/Math":18,"./common/Vec2":23,"./util/common":50,"./util/options":52}],5:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Joint; var common = require("./util/common"); /** * A joint edge is used to connect bodies and joints together in a joint graph * where each body is a node and each joint is an edge. A joint edge belongs to * a doubly linked list maintained in each attached body. Each joint has two * joint nodes, one for each attached body. * * @prop {Body} other provides quick access to the other body attached. * @prop {Joint} joint the joint * @prop {JointEdge} prev the previous joint edge in the body's joint list * @prop {JointEdge} next the next joint edge in the body's joint list */ function JointEdge() { this.other = null; this.joint = null; this.prev = null; this.next = null; } /** * @typedef {Object} JointDef * * Joint definitions are used to construct joints. * * @prop userData Use this to attach application specific data to your joints. * void userData; * @prop {boolean} collideConnected Set this flag to true if the attached bodies * should collide. * * @prop {Body} bodyA The first attached body. * @prop {Body} bodyB The second attached body. */ var DEFAULTS = { userData: null, collideConnected: false }; /** * The base joint class. Joints are used to constraint two bodies together in * various fashions. Some joints also feature limits and motors. * * @param {JointDef} def */ 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; } /** * Short-cut function to determine if either body is inactive. * * @returns {boolean} */ Joint.prototype.isActive = function() { return this.m_bodyA.isActive() && this.m_bodyB.isActive(); }; /** * Get the type of the concrete joint. * * @returns JointType */ Joint.prototype.getType = function() { return this.m_type; }; /** * Get the first body attached to this joint. * * @returns Body */ Joint.prototype.getBodyA = function() { return this.m_bodyA; }; /** * Get the second body attached to this joint. * * @returns Body */ Joint.prototype.getBodyB = function() { return this.m_bodyB; }; /** * Get the next joint the world joint list. * * @returns Joint */ 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; }; /** * Get collide connected. Note: modifying the collide connect flag won't work * correctly because the flag is only checked when fixture AABBs begin to * overlap. * * @returns {boolean} */ Joint.prototype.getCollideConnected = function() { return this.m_collideConnected; }; /** * Get the anchor point on bodyA in world coordinates. * * @return {Vec2} */ Joint.prototype.getAnchorA = function() {}; /** * Get the anchor point on bodyB in world coordinates. * * @return {Vec2} */ Joint.prototype.getAnchorB = function() {}; /** * Get the reaction force on bodyB at the joint anchor in Newtons. * * @param {float} inv_dt * @return {Vec2} */ Joint.prototype.getReactionForce = function(inv_dt) {}; /** * Get the reaction torque on bodyB in N*m. * * @param {float} inv_dt * @return {float} */ Joint.prototype.getReactionTorque = function(inv_dt) {}; /** * Shift the origin for any points stored in world coordinates. * * @param {Vec2} newOrigin */ Joint.prototype.shiftOrigin = function(newOrigin) {}; /** */ Joint.prototype.initVelocityConstraints = function(step) {}; /** */ Joint.prototype.solveVelocityConstraints = function(step) {}; /** * This returns true if the position errors are within tolerance. */ Joint.prototype.solvePositionConstraints = function(step) {}; },{"./util/common":50}],6:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Math = require("./common/Math"); var Rot = require("./common/Rot"); module.exports = Manifold; module.exports.clipSegmentToLine = clipSegmentToLine; module.exports.clipVertex = ClipVertex; module.exports.getPointStates = getPointStates; module.exports.PointState = PointState; // Manifold Type Manifold.e_circles = 0; Manifold.e_faceA = 1; Manifold.e_faceB = 2; // ContactFeature Type Manifold.e_vertex = 0; Manifold.e_face = 1; /** * A manifold for two touching convex shapes. Manifolds are created in `evaluate` * method of Contact subclasses. * * Supported manifold types are e_faceA or e_faceB for clip point versus plane * with radius and e_circles point versus point with radius. * * We store contacts in this way so that position correction can account for * movement, which is critical for continuous physics. All contact scenarios * must be expressed in one of these types. This structure is stored across time * steps, so we keep it small. * * @prop type e_circle, e_faceA, e_faceB * @prop localPoint Usage depends on manifold type:<br> * e_circles: the local center of circleA <br> * e_faceA: the center of faceA <br> * e_faceB: the center of faceB * @prop localNormal Usage depends on manifold type:<br> * e_circles: not used <br> * e_faceA: the normal on polygonA <br> * e_faceB: the normal on polygonB * @prop points The points of contact {ManifoldPoint[]} * @prop pointCount The number of manifold points */ function Manifold() { this.type; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } /** * A manifold point is a contact point belonging to a contact manifold. It holds * details related to the geometry and dynamics of the contact points. * * This structure is stored across time steps, so we keep it small. * * Note: impulses are used for internal caching and may not provide reliable * contact forces, especially for high speed collisions. * * @prop {Vec2} localPoint Usage depends on manifold type:<br> * e_circles: the local center of circleB<br> * e_faceA: the local center of cirlceB or the clip point of polygonB<br> * e_faceB: the clip point of polygonA. * @prop normalImpulse The non-penetration impulse * @prop tangentImpulse The friction impulse * @prop {ContactID} id Uniquely identifies a contact point between two shapes * to facilatate warm starting */ function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } /** * Contact ids to facilitate warm starting. * * @prop {ContactFeature} cf * @prop key Used to quickly compare contact ids. * */ function ContactID() { this.cf = new ContactFeature(); } Object.defineProperty(ContactID.prototype, "key", { get: function() { return this.cf.indexA + this.cf.indexB * 4 + this.cf.typeA * 16 + this.cf.typeB * 64; }, enumerable: true, configurable: true }); ContactID.prototype.set = function(o) { // this.key = o.key; this.cf.set(o.cf); }; /** * The features that intersect to form the contact point. * * @prop indexA Feature index on shapeA * @prop indexB Feature index on shapeB * @prop typeA The feature type on shapeA * @prop typeB The feature type on shapeB */ 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; }; /** * This is used to compute the current state of a contact manifold. * * @prop normal World vector pointing from A to B * @prop points World contact point (point of intersection) * @prop separations A negative value indicates overlap, in meters */ function WorldManifold() { this.normal; this.points = []; // [maxManifoldPoints] this.separations = []; } /** * Evaluate the manifold with supplied transforms. This assumes modest motion * from the original state. This does not change the point count, impulses, etc. * The radii must come from the shapes that generated the manifold. * * @param {WorldManifold} [wm] */ 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; // TODO: improve switch (this.type) { case Manifold.e_circles: normal = Vec2.neo(1, 0); var pointA = Transform.mulVec2(xfA, this.localPoint); var pointB = Transform.mulVec2(xfB, this.points[0].localPoint); var dist = Vec2.sub(pointB, pointA); if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) { normal.set(dist); normal.normalize(); } points[0] = Vec2.mid(pointA, pointB); separations[0] = -radiusB - radiusA; points.length = 1; separations.length = 1; break; case Manifold.e_faceA: normal = Rot.mulVec2(xfA.q, this.localNormal); var planePoint = Transform.mulVec2(xfA, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mulVec2(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).addMul(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).subMul(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mulVec2(xfB.q, this.localNormal); var planePoint = Transform.mulVec2(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mulVec2(xfA, this.points[i].localPoint); var cB = Vec2.combine(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.combine(1, clipPoint, -radiusA, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal); } points.length = this.pointCount; separations.length = this.pointCount; // Ensure normal points from A to B. normal.mul(-1); break; } wm.normal = normal; wm.points = points; wm.separations = separations; return wm; }; /** * This is used for determining the state of contact points. * * @prop {0} nullState Point does not exist * @prop {1} addState Point was added in the update * @prop {2} persistState Point persisted across the update * @prop {3} removeState Point was removed in the update */ var PointState = { // TODO: use constants nullState: 0, addState: 1, persistState: 2, removeState: 3 }; /** * Compute the point states given two manifolds. The states pertain to the * transition from manifold1 to manifold2. So state1 is either persist or remove * while state2 is either add or persist. * * @param {PointState[Settings.maxManifoldPoints]} state1 * @param {PointState[Settings.maxManifoldPoints]} state2 */ function getPointStates(state1, state2, manifold1, manifold2) { // for (var i = 0; i < Settings.maxManifoldPoints; ++i) { // state1[i] = PointState.nullState; // state2[i] = PointState.nullState; // } // Detect persists and removes. for (var i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; // ContactID 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; } } } // Detect persists and adds. for (var i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; // ContactID 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; } } } } /** * Used for computing contact manifolds. * * @prop {Vec2} v * @prop {ContactID} id */ 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); }; /** * Clipping for contact manifolds. Sutherland-Hodgman clipping. * * @param {ClipVertex[2]} vOut * @param {ClipVertex[2]} vIn */ function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { // Start with no output points var numOut = 0; // Calculate the distance of end points to the line var distance0 = Vec2.dot(normal, vIn[0].v) - offset; var distance1 = Vec2.dot(normal, vIn[1].v) - offset; // If the points are behind the plane if (distance0 <= 0) vOut[numOut++].set(vIn[0]); if (distance1 <= 0) vOut[numOut++].set(vIn[1]); // If the points are on different sides of the plane if (distance0 * distance1 < 0) { // Find intersection point of edge and plane var interp = distance0 / (distance0 - distance1); vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v); // VertexA is hitting edgeB. vOut[numOut].id.cf.indexA = vertexIndexA; vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; vOut[numOut].id.cf.typeA = Manifold.e_vertex; vOut[numOut].id.cf.typeB = Manifold.e_face; ++numOut; } return numOut; } },{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":50}],7:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; // TODO merge with World options? var Settings = exports; /** * Tuning constants based on meters-kilograms-seconds (MKS) units. */ // Collision /** * The maximum number of contact points between two convex shapes. Do not change * this value. */ Settings.maxManifoldPoints = 2; /** * The maximum number of vertices on a convex polygon. You cannot increase this * too much because BlockAllocator has a maximum object size. */ Settings.maxPolygonVertices = 12; /** * This is used to fatten AABBs in the dynamic tree. This allows proxies to move * by a small amount without triggering a tree adjustment. This is in meters. */ Settings.aabbExtension = .1; /** * This is used to fatten AABBs in the dynamic tree. This is used to predict the * future position based on the current displacement. This is a dimensionless * multiplier. */ Settings.aabbMultiplier = 2; /** * A small length used as a collision and constraint tolerance. Usually it is * chosen to be numerically significant, but visually insignificant. */ Settings.linearSlop = .005; Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop; /** * A small angle used as a collision and constraint tolerance. Usually it is * chosen to be numerically significant, but visually insignificant. */ Settings.angularSlop = 2 / 180 * Math.PI; /** * The radius of the polygon/edge shape skin. This should not be modified. * Making this smaller means polygons will have an insufficient buffer for * continuous collision. Making it larger may create artifacts for vertex * collision. */ Settings.polygonRadius = 2 * Settings.linearSlop; /** * Maximum number of sub-steps per contact in continuous physics simulation. */ Settings.maxSubSteps = 8; // Dynamics /** * Maximum number of contacts to be handled to solve a TOI impact. */ Settings.maxTOIContacts = 32; /** * Maximum iterations to solve a TOI. */ Settings.maxTOIIterations = 20; /** * Maximum iterations to find Distance. */ Settings.maxDistnceIterations = 20; /** * A velocity threshold for elastic collisions. Any collision with a relative * linear velocity below this threshold will be treated as inelastic. */ Settings.velocityThreshold = 1; /** * The maximum linear position correction used when solving constraints. This * helps to prevent overshoot. */ Settings.maxLinearCorrection = .2; /** * The maximum angular position correction used when solving constraints. This * helps to prevent overshoot. */ Settings.maxAngularCorrection = 8 / 180 * Math.PI; /** * The maximum linear velocity of a body. This limit is very large and is used * to prevent numerical problems. You shouldn't need to adjust this. */ Settings.maxTranslation = 2; Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation; /** * The maximum angular velocity of a body. This limit is very large and is used * to prevent numerical problems. You shouldn't need to adjust this. */ Settings.maxRotation = .5 * Math.PI; Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation; /** * This scale factor controls how fast overlap is resolved. Ideally this would * be 1 so that overlap is removed in one time step. However using values close * to 1 often lead to overshoot. */ Settings.baumgarte = .2; Settings.toiBaugarte = .75; // Sleep /** * The time that a body must be still before it will go to sleep. */ Settings.timeToSleep = .5; /** * A body cannot sleep if its linear velocity is above this tolerance. */ Settings.linearSleepTolerance = .01; Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2); /** * A body cannot sleep if its angular velocity is above this tolerance. */ Settings.angularSleepTolerance = 2 / 180 * Math.PI; Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2); },{}],8:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Shape; var Math = require("./common/Math"); /** * A shape is used for collision detection. You can create a shape however you * like. Shapes used for simulation in World are created automatically when a * Fixture is created. Shapes may encapsulate one or more child shapes. */ function Shape() { this.m_type; this.m_radius; } Shape.isValid = function(shape) { return !!shape; }; Shape.prototype.getRadius = function() { return this.m_radius; }; /** * Get the type of this shape. You can use this to down cast to the concrete * shape. * * @return the shape type. */ Shape.prototype.getType = function() { return this.m_type; }; /** * @deprecated Shapes should be treated as immutable. * * clone the concrete shape. */ Shape.prototype._clone = function() {}; /** * // Get the number of child primitives. */ Shape.prototype.getChildCount = function() {}; /** * Test a point for containment in this shape. This only works for convex * shapes. * * @param {Transform} xf The shape world transform. * @param p A point in world coordinates. */ Shape.prototype.testPoint = function(xf, p) {}; /** * Cast a ray against a child shape. * * @param {RayCastOutput} output The ray-cast results. * @param {RayCastInput} input The ray-cast input parameters. * @param {Transform} transform The transform to be applied to the shape. * @param childIndex The child shape index */ Shape.prototype.rayCast = function(output, input, transform, childIndex) {}; /** * Given a transform, compute the associated axis aligned bounding box for a * child shape. * * @param {AABB} aabb Returns the axis aligned box. * @param {Transform} xf The world transform of the shape. * @param childIndex The child shape */ Shape.prototype.computeAABB = function(aabb, xf, childIndex) {}; /** * Compute the mass properties of this shape using its dimensions and density. * The inertia tensor is computed about the local origin. * * @param {MassData} massData Returns the mass data for this shape. * @param density The density in kilograms per meter squared. */ Shape.prototype.computeMass = function(massData, density) {}; /** * @param {DistanceProxy} proxy */ Shape.prototype.computeDistanceProxy = function(proxy) {}; },{"./common/Math":18}],9:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Math = require("./common/Math"); var Body = require("./Body"); var Contact = require("./Contact"); var Joint = require("./Joint"); var TimeOfImpact = require("./collision/TimeOfImpact"); var TOIInput = TimeOfImpact.Input; var TOIOutput = TimeOfImpact.Output; var Distance = require("./collision/Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TimeStep(dt) { this.dt = 0; // time step this.inv_dt = 0; // inverse time step (0 if dt == 0) this.velocityIterations = 0; this.positionIterations = 0; this.warmStarting = false; this.blockSolve = true; // timestep ratio for variable timestep 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; }; /** * Finds and solves islands. An island is a connected subset of the world. * * @param {World} world */ function Solver(world) { this.m_world = world; this.m_stack = []; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; } Solver.prototype.clear = function() { this.m_stack.length = 0; this.m_bodies.length = 0; this.m_contacts.length = 0; this.m_joints.length = 0; }; Solver.prototype.addBody = function(body) { _ASSERT && common.assert(body instanceof Body, "Not a Body!", body); this.m_bodies.push(body); }; Solver.prototype.addContact = function(contact) { _ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact); this.m_contacts.push(contact); }; Solver.prototype.addJoint = function(joint) { _ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint); this.m_joints.push(joint); }; /** * @param {TimeStep} step */ Solver.prototype.solveWorld = function(step) { var world = this.m_world; // Clear all the island flags. 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; } // Build and simulate all awake islands. 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; } // The seed can be dynamic or kinematic. if (seed.isStatic()) { continue; } // Reset island and stack. this.clear(); stack.push(seed); seed.m_islandFlag = true; // Perform a depth first search (DFS) on the constraint graph. while (stack.length > 0) { // Grab the next body off the stack and add it to the island. var b = stack.pop(); _ASSERT && common.assert(b.isActive() == true); this.addBody(b); // Make sure the body is awake. b.setAwake(true); // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b.isStatic()) { continue; } // Search all contacts connected to this body. for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; // Has this contact already been added to an island? if (contact.m_islandFlag) { continue; } // Is this contact solid and touching? if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } // Skip sensors. 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; // Was the other body already added to this island? if (other.m_islandFlag) { continue; } // _ASSERT && common.assert(stack.length < world.m_bodyCount); stack.push(other); other.m_islandFlag = true; } // Search all joints connect to this body. for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } var other = je.other; // Don't simulate joints connected to inactive bodies. if (other.isActive() == false) { continue; } this.addJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) { continue; } // _ASSERT && common.assert(stack.length < world.m_bodyCount); stack.push(other); other.m_islandFlag = true; } } this.solveIsland(step); // Post solve cleanup. for (var i = 0; i < this.m_bodies.length; ++i) { // Allow static bodies to participate in other islands. // TODO: are they added at all? var b = this.m_bodies[i]; if (b.isStatic()) { b.m_islandFlag = false; } } } }; /** * @param {TimeStep} step */ Solver.prototype.solveIsland = function(step) { // B2: Island Solve var world = this.m_world; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var h = step.dt; // Integrate velocities and apply damping. Initialize the body state. 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; // Store positions for continuous collision. body.m_sweep.c0.set(body.m_sweep.c); body.m_sweep.a0 = body.m_sweep.a; if (body.isDynamic()) { // Integrate velocities. v.addMul(h * body.m_gravityScale, gravity); v.addMul(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; /** * <pre> * Apply damping. * ODE: dv/dt + c * v = 0 * Solution: v(t) = v0 * exp(-c * t) * Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) * v2 = exp(-c * dt) * v1 * Pade approximation: * v2 = v1 * 1 / (1 + c * dt) * </pre> */ v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(step); } _DEBUG && this.printBodies("M: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(step); } _DEBUG && this.printBodies("R: "); if (step.warmStarting) { // Warm start. 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: "); // Solve velocity constraints for (var i = 0; i < step.velocityIterations; ++i) { for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; joint.solveVelocityConstraints(step); } for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(step); } } _DEBUG && this.printBodies("D: "); // Store impulses for warm starting for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.storeConstraintImpulses(step); } _DEBUG && this.printBodies("C: "); // Integrate positions 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; // Check for large velocities 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; } // Integrate c.addMul(h, v); a += h * w; body.c_position.c.set(c); body.c_position.a = a; body.c_velocity.v.set(v); body.c_velocity.w = w; } _DEBUG && this.printBodies("B: "); // Solve position constraints 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); } // We can't expect minSpeparation >= -Settings.linearSlop because we don't // push the separation above -Settings.linearSlop. 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) { // Exit early if the position errors are small. positionSolved = true; break; } } _DEBUG && this.printBodies("L: "); // Copy state buffers back to the bodies for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.set(body.c_position.c); body.m_sweep.a = body.c_position.a; body.m_linearVelocity.set(body.c_velocity.v); body.m_angularVelocity = body.c_velocity.w; body.synchronizeTransform(); } this.postSolveIsland(); if (allowSleep) { var minSleepTime = Infinity; var linTolSqr = Settings.linearSleepToleranceSqr; var angTolSqr = Settings.angularSleepToleranceSqr; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; if (body.isStatic()) { continue; } if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) { body.m_sleepTime = 0; minSleepTime = 0; } else { body.m_sleepTime += h; minSleepTime = Math.min(minSleepTime, body.m_sleepTime); } } if (minSleepTime >= Settings.timeToSleep && positionSolved) { for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.setAwake(false); } } } }; Solver.prototype.printBodies = function(tag) { for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y); } }; var s_subStep = new TimeStep(); // reuse /** * Find TOI contacts and solve them. * * @param {TimeStep} step */ Solver.prototype.solveWorldTOI = function(step) { var world = this.m_world; if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; } for (var c = world.m_contactList; c; c = c.m_next) { // Invalidate TOI c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } // Find TOI events and solve them. for (;;) { // Find the first TOI. var minContact = null; // Contact var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { // Is this contact disabled? if (c.isEnabled() == false) { continue; } // Prevent excessive sub-stepping. if (c.m_toiCount > Settings.maxSubSteps) { continue; } var alpha = 1; if (c.m_toiFlag) { // This contact has a valid cached TOI. alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); // Is there a sensor? 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(); // Is at least one body active (awake and dynamic or kinematic)? if (activeA == false && activeB == false) { continue; } var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); // Are these two non-bullet dynamic bodies? if (collideA == false && collideB == false) { continue; } // Compute the TOI for this contact. // Put the sweeps onto the same time interval. var alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } _ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; // Compute the time of impact in interval [0, minTOI] var input = new TOIInput(); // TODO: reuse 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(); // TODO: reuse TimeOfImpact(output, input); // Beta is the fraction of the remaining portion of the [time?]. var beta = output.t; if (output.state == TOIOutput.e_touching) { alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1); } else { alpha = 1; } c.m_toi = alpha; c.m_toiFlag = true; } if (alpha < minAlpha) { // This is the minimum TOI found so far. minContact = c; minAlpha = alpha; } } if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) { // No more TOI events. Done! world.m_stepComplete = true; break; } // Advance the bodies to the TOI. 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); // The TOI contact likely has some new contact points. minContact.update(world); minContact.m_toiFlag = false; ++minContact.m_toiCount; // Is the contact solid? if (minContact.isEnabled() == false || minContact.isTouching() == false) { // Restore the sweeps. minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); // Build the island this.clear(); this.addBody(bA); this.addBody(bB); this.addContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; // Get contacts on bodyA and bodyB. 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) { // if (this.m_bodyCount == this.m_bodyCapacity) { break; } // if (this.m_contactCount == this.m_contactCapacity) { break; } var contact = ce.contact; // Has this contact already been added to the island? if (contact.m_islandFlag) { continue; } // Only add if either is static, kinematic or bullet. var other = ce.other; if (other.isDynamic() && !body.isBullet() && !other.isBullet()) { continue; } // Skip sensors. var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } // Tentatively advance the body to the TOI. var backup = other.m_sweep.clone(); if (other.m_islandFlag == false) { other.advance(minAlpha); } // Update the contact points contact.update(world); // Was the contact disabled by the user? // Are there contact points? if (contact.isEnabled() == false || contact.isTouching() == false) { other.m_sweep.set(backup); other.synchronizeTransform(); continue; } // Add the contact to the island contact.m_islandFlag = true; this.addContact(contact); // Has the other body already been added to the island? if (other.m_islandFlag) { continue; } // Add the other body to the island. 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); // Reset island flags and synchronize broad-phase proxies. 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(); // Invalidate all contact TOIs on this displaced body. for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } // Commit fixture proxy movements to the broad-phase so that new contacts // are created. // Also, some contacts can be destroyed. 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; } }; /** * @param {TimeStep} subStep * @param toiA * @param toiB */ Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { var world = this.m_world; // Initialize the body state. 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); } // Solve position constraints. 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); } // We can't expect minSpeparation >= -Settings.linearSlop because we don't // push the separation above -Settings.linearSlop. var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop; if (contactsOkay) { break; } } if (false) { // Is the new position really safe? 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; } } } // Leap of faith to new safe state. 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; // No warm starting is needed for TOI events because warm // starting impulses were applied in the discrete solver. for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(subStep); } // Solve velocity constraints. 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); } } // Don't store the TOI contact forces for warm starting // because they can be quite large. var h = subStep.dt; // Integrate positions 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; // Check for large velocities 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; } // Integrate c.addMul(h, v); a += h * w; body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; // Sync bodies body.m_sweep.c = c; body.m_sweep.a = a; body.m_linearVelocity = v; body.m_angularVelocity = w; body.synchronizeTransform(); } this.postSolveIsland(); }; /** * Contact impulses for reporting. Impulses are used instead of forces because * sub-step forces may approach infinity for rigid body collisions. These match * up one-to-one with the contact points in Manifold. */ function ContactImpulse() { this.normalImpulses = []; this.tangentImpulses = []; } Solver.prototype.postSolveIsland = function() { // TODO: report contact.v_points instead of new object? var impulse = new ContactImpulse(); for (var c = 0; c < this.m_contacts.length; ++c) { var contact = this.m_contacts[c]; for (var p = 0; p < contact.v_points.length; ++p) { impulse.normalImpulses.push(contact.v_points[p].normalImpulse); impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse); } this.m_world.postSolve(contact, impulse); } }; },{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/common":50}],10:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var BroadPhase = require("./collision/BroadPhase"); var Solver = require("./Solver"); var Body = require("./Body"); var Contact = require("./Contact"); /** * @typedef {Object} WorldDef * * @prop {Vec2} [gravity = { x : 0, y : 0}] * @prop {boolean} [allowSleep = true] * @prop {boolean} [warmStarting = false] * @prop {boolean} [continuousPhysics = false] * @prop {boolean} [subStepping = false] * @prop {boolean} [blockSolve = true] * @prop {int} [velocityIterations = 8] For the velocity constraint solver. * @prop {int} [positionIterations = 3] For the position constraint solver. */ var WorldDef = { gravity: Vec2.zero(), allowSleep: true, warmStarting: true, continuousPhysics: true, subStepping: false, blockSolve: true, velocityIterations: 8, positionIterations: 3 }; /** * @param {WordDef|Vec2} def World definition or gravity vector. */ 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; // These are for debugging the solver. 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; // Broad-phase callback. this.addPair = this.createContact.bind(this); } /** * Get the world body list. With the returned body, use Body.getNext to get the * next body in the world list. A null body indicates the end of the list. * * @return the head of the world body list. */ World.prototype.getBodyList = function() { return this.m_bodyList; }; /** * Get the world joint list. With the returned joint, use Joint.getNext to get * the next joint in the world list. A null joint indicates the end of the list. * * @return the head of the world joint list. */ World.prototype.getJointList = function() { return this.m_jointList; }; /** * Get the world contact list. With the returned contact, use Contact.getNext to * get the next contact in the world list. A null contact indicates the end of * the list. * * @return the head of the world contact list. Warning: contacts are created and * destroyed in the middle of a time step. Use ContactListener to avoid * missing contacts. */ World.prototype.getContactList = function() { return this.m_contactList; }; World.prototype.getBodyCount = function() { return this.m_bodyCount; }; World.prototype.getJointCount = function() { return this.m_jointCount; }; /** * Get the number of contacts (each may have 0 or more contact points). */ World.prototype.getContactCount = function() { return this.m_contactCount; }; /** * Change the global gravity vector. */ World.prototype.setGravity = function(gravity) { this.m_gravity = gravity; }; /** * Get the global gravity vector. */ World.prototype.getGravity = function() { return this.m_gravity; }; /** * Is the world locked (in the middle of a time step). */ World.prototype.isLocked = function() { return this.m_locked; }; /** * Enable/disable sleep. */ 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; }; /** * Enable/disable warm starting. For testing. */ World.prototype.setWarmStarting = function(flag) { this.m_warmStarting = flag; }; World.prototype.getWarmStarting = function() { return this.m_warmStarting; }; /** * Enable/disable continuous physics. For testing. */ World.prototype.setContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; World.prototype.getContinuousPhysics = function() { return this.m_continuousPhysics; }; /** * Enable/disable single stepped continuous physics. For testing. */ World.prototype.setSubStepping = function(flag) { this.m_subStepping = flag; }; World.prototype.getSubStepping = function() { return this.m_subStepping; }; /** * Set flag to control automatic clearing of forces after each time step. */ World.prototype.setAutoClearForces = function(flag) { this.m_clearForces = flag; }; /** * Get the flag that controls automatic clearing of forces after each time step. */ World.prototype.getAutoClearForces = function() { return this.m_clearForces; }; /** * Manually clear the force buffer on all bodies. By default, forces are cleared * automatically after each call to step. The default behavior is modified by * calling setAutoClearForces. The purpose of this function is to support * sub-stepping. Sub-stepping is often used to maintain a fixed sized time step * under a variable frame-rate. When you perform sub-stepping you will disable * auto clearing of forces and instead call clearForces after all sub-steps are * complete in one pass of your game loop. * * @see setAutoClearForces */ World.prototype.clearForces = function() { for (var body = this.m_bodyList; body; body = body.getNext()) { body.m_force.setZero(); body.m_torque = 0; } }; /** * @function World~rayCastCallback * * @param fixture */ /** * Query the world for all fixtures that potentially overlap the provided AABB. * * @param {World~queryCallback} queryCallback Called for each fixture * found in the query AABB. It may return `false` to terminate the * query. * * @param aabb The query box. */ World.prototype.queryAABB = function(aabb, queryCallback) { _ASSERT && common.assert(typeof queryCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.query(aabb, function(proxyId) { //TODO GC var proxy = broadPhase.getUserData(proxyId); // FixtureProxy return queryCallback(proxy.fixture); }); }; /** * @function World~rayCastCallback * * Callback class for ray casts. See World.rayCast * * Called for each fixture found in the query. You control how the ray cast * proceeds by returning a float: return -1: ignore this fixture and continue * return 0: terminate the ray cast return fraction: clip the ray to this point * return 1: don't clip the ray and continue * * @param fixture The fixture hit by the ray * @param point The point of initial intersection * @param normal The normal vector at the point of intersection * @param fraction * * @return {float} -1 to filter, 0 to terminate, fraction to clip the ray for * closest hit, 1 to continue */ /** * * Ray-cast the world for all fixtures in the path of the ray. Your callback * controls whether you get the closest point, any point, or n-points. The * ray-cast ignores shapes that contain the starting point. * * @param {World~RayCastCallback} reportFixtureCallback A user implemented * callback function. * @param point1 The ray starting point * @param point2 The ray ending point */ 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) { // TODO GC var proxy = broadPhase.getUserData(proxyId); // FixtureProxy var fixture = proxy.fixture; var index = proxy.childIndex; var output = {}; // TODO GC 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; }); }; /** * Get the number of broad-phase proxies. */ World.prototype.getProxyCount = function() { return this.m_broadPhase.getProxyCount(); }; /** * Get the height of broad-phase dynamic tree. */ World.prototype.getTreeHeight = function() { return this.m_broadPhase.getTreeHeight(); }; /** * Get the balance of broad-phase dynamic tree. * * @returns {int} */ World.prototype.getTreeBalance = function() { return this.m_broadPhase.getTreeBalance(); }; /** * Get the quality metric of broad-phase dynamic tree. The smaller the better. * The minimum is 1. * * @returns {float} */ World.prototype.getTreeQuality = function() { return this.m_broadPhase.getTreeQuality(); }; /** * Shift the world origin. Useful for large worlds. The body shift formula is: * position -= newOrigin * * @param {Vec2} newOrigin The new origin with respect to the old origin */ 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); }; /** * Create a rigid body given a definition. No reference to the definition is * retained. * * Warning: This function is locked during callbacks. * * @param {BodyDef|Vec2} def Body definition or position. * @param {float} angle Body angle if def is position. */ 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); // Add to world doubly linked list. 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); }; /** * Destroy a rigid body given a definition. No reference to the definition is * retained. * * Warning: This automatically deletes all associated shapes and joints. * * Warning: This function is locked during callbacks. * * @param {Body} b */ 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; } // Delete the attached joints. 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; // Delete the attached contacts. 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; // Delete the attached fixtures. This destroys broad-phase proxies. 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; // Remove world body list. if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == this.m_bodyList) { this.m_bodyList = b.m_next; } b.m_destroyed = true; --this.m_bodyCount; this.publish("remove-body", b); return true; }; /** * Create a joint to constrain bodies together. No reference to the definition * is retained. This may cause the connected bodies to cease colliding. * * Warning: This function is locked during callbacks. * * @param {Joint} join * @param {Body} bodyB * @param {Body} bodyA */ 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; } // Connect to the world list. 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; // Connect to the bodies' doubly linked lists. 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 the joint prevents collisions, then flag any contacts for filtering. if (joint.m_collideConnected == false) { for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) { if (edge.other == joint.m_bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.flagForFiltering(); } } } // Note: creating a joint doesn't wake the bodies. return joint; }; /** * Destroy a joint. This may cause the connected bodies to begin colliding. * Warning: This function is locked during callbacks. * * @param {Joint} join */ World.prototype.destroyJoint = function(joint) { _ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } // Remove from the doubly linked list. 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; } // Disconnect from bodies. var bodyA = joint.m_bodyA; var bodyB = joint.m_bodyB; // Wake up connected bodies. bodyA.setAwake(true); bodyB.setAwake(true); // Remove from body 1. 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; // Remove from body 2 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 the joint prevents collisions, then flag any contacts for filtering. if (joint.m_collideConnected == false) { var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge.contact.flagForFiltering(); } edge = edge.next; } } this.publish("remove-joint", joint); }; var s_step = new Solver.TimeStep(); // reuse /** * Take a time step. This performs collision detection, integration, and * constraint solution. * * Broad-phase, narrow-phase, solve and solve time of impacts. * * @param {float} timeStep Time step, this should not vary. * @param {int} velocityIterations * @param {int} positionIterations */ World.prototype.step = function(timeStep, velocityIterations, positionIterations) { if ((velocityIterations | 0) !== velocityIterations) { // TODO: remove this in future velocityIterations = 0; } velocityIterations = velocityIterations || this.m_velocityIterations; positionIterations = positionIterations || this.m_positionIterations; // TODO: move this to testbed this.m_stepCount++; // If new fixtures were added, we need to find the new contacts. 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; // Update contacts. This is where some contacts are destroyed. this.updateContacts(); // Integrate velocities, solve velocity constraints, and integrate positions. if (this.m_stepComplete && timeStep > 0) { this.m_solver.solveWorld(s_step); // Synchronize fixtures, check for out of range bodies. for (var b = this.m_bodyList; b; b = b.getNext()) { // If a body was not in an island then it did not move. if (b.m_islandFlag == false) { continue; } if (b.isStatic()) { continue; } // Update fixtures (for broad-phase). b.synchronizeFixtures(); } // Look for new contacts. this.findNewContacts(); } // Handle TOI events. if (this.m_continuousPhysics && timeStep > 0) { this.m_solver.solveWorldTOI(s_step); } if (this.m_clearForces) { this.clearForces(); } this.m_locked = false; }; /** * Call this method to find new contacts. */ World.prototype.findNewContacts = function() { this.m_broadPhase.updatePairs(this.addPair); }; /** * @private * * @param {FixtureProxy} proxyA * @param {FixtureProxy} proxyB */ 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(); // Are the fixtures on the same body? if (bodyA == bodyB) { return; } // TODO_ERIN use a hash table to remove a potential bottleneck when both // bodies have a lot of contacts. // Does a contact already exist? var edge = bodyB.getContactList(); // ContactEdge 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) { // A contact already exists. return; } if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) { // A contact already exists. return; } } edge = edge.next; } if (bodyB.shouldCollide(bodyA) == false) { return; } if (fixtureB.shouldCollide(fixtureA) == false) { return; } // Call the factory. var contact = Contact.create(fixtureA, indexA, fixtureB, indexB); if (contact == null) { return; } // Insert into the world. 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; }; /** * Removes old non-overlapping contacts, applies filters and updates contacts. */ World.prototype.updateContacts = function() { // Update awake contacts. 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(); // Is this contact flagged for filtering? if (c.m_filterFlag) { if (bodyB.shouldCollide(bodyA) == false) { this.destroyContact(c); continue; } if (fixtureB.shouldCollide(fixtureA) == false) { this.destroyContact(c); continue; } // Clear the filtering flag. c.m_filterFlag = false; } var activeA = bodyA.isAwake() && !bodyA.isStatic(); var activeB = bodyB.isAwake() && !bodyB.isStatic(); // At least one body must be awake and it must be dynamic or kinematic. 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); // Here we destroy contacts that cease to overlap in the broad-phase. if (overlap == false) { this.destroyContact(c); continue; } // The contact persists. c.update(this); } }; /** * @param {Contact} contact */ World.prototype.destroyContact = function(contact) { Contact.destroy(contact, this); // Remove from the world. 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; /** * Register an event listener. * * @param {string} name * @param {function} listener */ 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; }; /** * Remove an event listener. * * @param {string} name * @param {function} listener */ 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; }; /** * @event World#remove-body * @event World#remove-joint * @event World#remove-fixture * * Joints and fixtures are destroyed when their associated body is destroyed. * Register a destruction listener so that you may nullify references to these * joints and shapes. * * `function(object)` is called when any joint or fixture is about to * be destroyed due to the destruction of one of its attached or parent bodies. */ /** * @private * @param {Contact} contact */ World.prototype.beginContact = function(contact) { this.publish("begin-contact", contact); }; /** * @event World#begin-contact * * Called when two fixtures begin to touch. * * Implement contact callbacks to get contact information. You can use these * results for things like sounds and game logic. You can also get contact * results by traversing the contact lists after the time step. However, you * might miss some contacts because continuous physics leads to sub-stepping. * Additionally you may receive multiple callbacks for the same contact in a * single time step. You should strive to make your callbacks efficient because * there may be many callbacks per time step. * * Warning: You cannot create/destroy world entities inside these callbacks. */ /** * @private * @param {Contact} contact */ World.prototype.endContact = function(contact) { this.publish("end-contact", contact); }; /** * @event World#end-contact * * Called when two fixtures cease to touch. * * Implement contact callbacks to get contact information. You can use these * results for things like sounds and game logic. You can also get contact * results by traversing the contact lists after the time step. However, you * might miss some contacts because continuous physics leads to sub-stepping. * Additionally you may receive multiple callbacks for the same contact in a * single time step. You should strive to make your callbacks efficient because * there may be many callbacks per time step. * * Warning: You cannot create/destroy world entities inside these callbacks. */ /** * @private * @param {Contact} contact * @param {Manifold} oldManifold */ World.prototype.preSolve = function(contact, oldManifold) { this.publish("pre-solve", contact, oldManifold); }; /** * @event World#pre-solve * * This is called after a contact is updated. This allows you to inspect a * contact before it goes to the solver. If you are careful, you can modify the * contact manifold (e.g. disable contact). A copy of the old manifold is * provided so that you can detect changes. Note: this is called only for awake * bodies. Note: this is called even when the number of contact points is zero. * Note: this is not called for sensors. Note: if you set the number of contact * points to zero, you will not get an endContact callback. However, you may get * a beginContact callback the next step. * * Warning: You cannot create/destroy world entities inside these callbacks. */ /** * @private * @param {Contact} contact * @param {ContactImpulse} impulse */ World.prototype.postSolve = function(contact, impulse) { this.publish("post-solve", contact, impulse); }; },{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/common":50,"./util/options":52}],11:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); module.exports = AABB; function AABB(lower, upper) { if (!(this instanceof AABB)) { return new AABB(lower, upper); } this.lowerBound = Vec2.zero(); this.upperBound = Vec2.zero(); if (typeof lower === "object") { this.lowerBound.set(lower); } if (typeof upper === "object") { this.upperBound.set(upper); } } /** * Verify that the bounds are sorted. */ AABB.prototype.isValid = function() { return AABB.isValid(this); }; AABB.isValid = function(aabb) { var d = Vec2.sub(aabb.upperBound, aabb.lowerBound); var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound); return valid; }; AABB.assert = function(o) { if (!_ASSERT) return; if (!AABB.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid AABB!"); } }; /** * Get the center of the AABB. */ AABB.prototype.getCenter = function() { return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5); }; /** * Get the extents of the AABB (half-widths). */ AABB.prototype.getExtents = function() { return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5); }; /** * Get the perimeter length. */ AABB.prototype.getPerimeter = function() { return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y); }; /** * Combine one or two AABB into this one. */ AABB.prototype.combine = function(a, b) { var lowerA = a.lowerBound; var upperA = a.upperBound; var lowerB = b.lowerBound; var upperB = b.upperBound; var lowerX = Math.min(lowerA.x, lowerB.x); var lowerY = Math.min(lowerA.y, lowerB.y); var upperX = Math.max(upperB.x, upperA.x); var upperY = Math.max(upperB.y, upperA.y); this.lowerBound.set(lowerX, lowerY); this.upperBound.set(upperX, upperY); }; AABB.prototype.combinePoints = function(a, b) { this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y)); this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y)); }; AABB.prototype.set = function(aabb) { this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y); this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y); }; AABB.prototype.contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; AABB.prototype.extend = function(value) { AABB.extend(this, value); }; AABB.extend = function(aabb, value) { aabb.lowerBound.x -= value; aabb.lowerBound.y -= value; aabb.upperBound.x += value; aabb.upperBound.y += value; }; AABB.testOverlap = function(a, b) { var d1x = b.lowerBound.x - a.upperBound.x; var d2x = a.lowerBound.x - b.upperBound.x; var d1y = b.lowerBound.y - a.upperBound.y; var d2y = a.lowerBound.y - b.upperBound.y; if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) { return false; } return true; }; AABB.areEqual = function(a, b) { return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound); }; AABB.diff = function(a, b) { var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x)); var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y)); var wA = a.upperBound.x - a.lowerBound.x; var hA = a.upperBound.y - a.lowerBound.y; var wB = b.upperBound.x - b.lowerBound.x; var hB = b.upperBound.y - b.lowerBound.y; return wA * hA + wB * hB - wD * hD; }; /** * @typedef RayCastInput * * Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). * * @prop {Vec2} p1 * @prop {Vec2} p2 * @prop {number} maxFraction */ /** * @typedef RayCastInput * * Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and * p2 come from RayCastInput. * * @prop {Vec2} normal * @prop {number} fraction */ /** * @param {RayCastOutput} output * @param {RayCastInput} input * @returns {boolean} */ AABB.prototype.rayCast = function(output, input) { // From Real-time Collision Detection, p179. 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) { // Parallel. 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; // Sign of the normal vector. var s = -1; if (t1 > t2) { var temp = t1; t1 = t2, t2 = temp; s = 1; } // Push the min up if (t1 > tmin) { normal.setZero(); normal[f] = s; tmin = t1; } // Pull the max down tmax = Math.min(tmax, t2); if (tmin > tmax) { return false; } } } // Does the ray start inside the box? // Does the ray intersect beyond the max fraction? if (tmin < 0 || input.maxFraction < tmin) { return false; } // Intersection. output.fraction = tmin; output.normal = normal; return true; }; AABB.prototype.toString = function() { return JSON.stringify(this); }; },{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Math = require("../common/Math"); var AABB = require("./AABB"); var DynamicTree = require("./DynamicTree"); module.exports = BroadPhase; /** * The broad-phase wraps and extends a dynamic-tree keep to track of moved * objects and query them on update. */ function BroadPhase() { this.m_tree = new DynamicTree(); this.m_proxyCount = 0; this.m_moveBuffer = []; this.queryCallback = this.queryCallback.bind(this); } /** * Get user data from a proxy. Returns null if the id is invalid. */ BroadPhase.prototype.getUserData = function(proxyId) { return this.m_tree.getUserData(proxyId); }; /** * Test overlap of fat AABBs. */ 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); }; /** * Get the fat AABB for a proxy. */ BroadPhase.prototype.getFatAABB = function(proxyId) { return this.m_tree.getFatAABB(proxyId); }; /** * Get the number of proxies. */ BroadPhase.prototype.getProxyCount = function() { return this.m_proxyCount; }; /** * Get the height of the embedded tree. */ BroadPhase.prototype.getTreeHeight = function() { return this.m_tree.getHeight(); }; /** * Get the balance (integer) of the embedded tree. */ BroadPhase.prototype.getTreeBalance = function() { return this.m_tree.getMaxBalance(); }; /** * Get the quality metric of the embedded tree. */ BroadPhase.prototype.getTreeQuality = function() { return this.m_tree.getAreaRatio(); }; /** * Query an AABB for overlapping proxies. The callback class is called for each * proxy that overlaps the supplied AABB. */ BroadPhase.prototype.query = function(aabb, queryCallback) { this.m_tree.query(aabb, queryCallback); }; /** * Ray-cast against the proxies in the tree. This relies on the callback to * perform a exact ray-cast in the case were the proxy contains a shape. The * callback also performs the any collision filtering. This has performance * roughly equal to k * log(n), where k is the number of collisions and n is the * number of proxies in the tree. * * @param input The ray-cast input data. The ray extends from p1 to p1 + * maxFraction * (p2 - p1). * @param rayCastCallback A function that is called for each proxy that is hit by * the ray. */ BroadPhase.prototype.rayCast = function(input, rayCastCallback) { this.m_tree.rayCast(input, rayCastCallback); }; /** * Shift the world origin. Useful for large worlds. The shift formula is: * position -= newOrigin * * @param newOrigin The new origin with respect to the old origin */ BroadPhase.prototype.shiftOrigin = function(newOrigin) { this.m_tree.shiftOrigin(newOrigin); }; /** * Create a proxy with an initial AABB. Pairs are not reported until UpdatePairs * is called. */ 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; }; /** * Destroy a proxy. It is up to the client to remove any pairs. */ BroadPhase.prototype.destroyProxy = function(proxyId) { this.unbufferMove(proxyId); this.m_proxyCount--; this.m_tree.destroyProxy(proxyId); }; /** * Call moveProxy as many times as you like, then when you are done call * UpdatePairs to finalized the proxy pairs (for your time step). */ 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); } }; /** * Call to trigger a re-processing of it's pairs on the next call to * UpdatePairs. */ 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; } } }; /** * @function BroadPhase~addPair * @param {Object} userDataA * @param {Object} userDataB */ /** * Update the pairs. This results in pair callbacks. This can only add pairs. * * @param {BroadPhase~AddPair} addPairCallback */ BroadPhase.prototype.updatePairs = function(addPairCallback) { _ASSERT && common.assert(typeof addPairCallback === "function"); this.m_callback = addPairCallback; // Perform tree queries for all moving proxies. while (this.m_moveBuffer.length > 0) { this.m_queryProxyId = this.m_moveBuffer.pop(); if (this.m_queryProxyId === null) { continue; } // We have to query the tree with the fat AABB so that // we don't fail to create a pair that may touch later. var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId); // Query tree, create pairs and add them pair buffer. this.m_tree.query(fatAABB, this.queryCallback); } }; BroadPhase.prototype.queryCallback = function(proxyId) { // A proxy cannot form a pair with itself. if (proxyId == this.m_queryProxyId) { return true; } var proxyIdA = Math.min(proxyId, this.m_queryProxyId); var proxyIdB = Math.max(proxyId, this.m_queryProxyId); // TODO: Skip any duplicate pairs. var userDataA = this.m_tree.getUserData(proxyIdA); var userDataB = this.m_tree.getUserData(proxyIdB); // Send the pairs back to the client. this.m_callback(userDataA, userDataB); return true; }; },{"../Settings":7,"../common/Math":18,"../util/common":50,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Distance; module.exports.Input = DistanceInput; module.exports.Output = DistanceOutput; module.exports.Proxy = DistanceProxy; module.exports.Cache = SimplexCache; var Settings = require("../Settings"); var common = require("../util/common"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); /** * GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. */ stats.gjkCalls = 0; stats.gjkIters = 0; stats.gjkMaxIters = 0; /** * Input for Distance. You have to option to use the shape radii in the * computation. Even */ function DistanceInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.transformA = null; this.transformB = null; this.useRadii = false; } /** * Output for Distance. * * @prop {Vec2} pointA closest point on shapeA * @prop {Vec2} pointB closest point on shapeB * @prop distance * @prop iterations number of GJK iterations used */ function DistanceOutput() { this.pointA = Vec2.zero(); this.pointB = Vec2.zero(); this.distance; this.iterations; } /** * Used to warm start Distance. Set count to zero on first call. * * @prop {number} metric length or area * @prop {array} indexA vertices on shape A * @prop {array} indexB vertices on shape B * @prop {number} count */ function SimplexCache() { this.metric = 0; this.indexA = []; this.indexB = []; this.count = 0; } /** * Compute the closest points between two shapes. Supports any combination of: * CircleShape, PolygonShape, EdgeShape. The simplex cache is input/output. On * the first call set SimplexCache.count to zero. * * @param {DistanceOutput} output * @param {SimplexCache} cache * @param {DistanceInput} input */ function Distance(output, cache, input) { ++stats.gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var xfA = input.transformA; var xfB = input.transformB; // Initialize the simplex. var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); // Get simplex vertices as an array. var vertices = simplex.m_v; // SimplexVertex var k_maxIters = Settings.maxDistnceIterations; // These store the vertices of the last simplex so that we // can check for duplicates and prevent cycling. var saveA = []; var saveB = []; // int[3] var saveCount = 0; var distanceSqr1 = Infinity; var distanceSqr2 = Infinity; // Main iteration loop. var iter = 0; while (iter < k_maxIters) { // Copy simplex so we can identify duplicates. saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } simplex.solve(); // If we have 3 points, then the origin is in the corresponding triangle. if (simplex.m_count == 3) { break; } // Compute closest point. var p = simplex.getClosestPoint(); distanceSqr2 = p.lengthSquared(); // Ensure progress if (distanceSqr2 >= distanceSqr1) {} distanceSqr1 = distanceSqr2; // Get search direction. var d = simplex.getSearchDirection(); // Ensure the search direction is numerically fit. if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) { // The origin is probably contained by a line segment // or triangle. Thus the shapes are overlapped. // We can't return zero here even though there may be overlap. // In case the simplex is a point, segment, or triangle it is difficult // to determine if the origin is contained in the CSO or very close to it. break; } // Compute a tentative new simplex vertex using support points. var vertex = vertices[simplex.m_count]; // SimplexVertex vertex.indexA = proxyA.getSupport(Rot.mulTVec2(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mulVec2(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulTVec2(xfB.q, d)); vertex.wB = Transform.mulVec2(xfB, proxyB.getVertex(vertex.indexB)); vertex.w = Vec2.sub(vertex.wB, vertex.wA); // Iteration count is equated to the number of support point calls. ++iter; ++stats.gjkIters; // Check for duplicate support points. This is the main termination // criteria. var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) { duplicate = true; break; } } // If we found a duplicate support point we must exit to avoid cycling. if (duplicate) { break; } // New vertex is ok and needed. ++simplex.m_count; } stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter); // Prepare output. simplex.getWitnessPoints(output.pointA, output.pointB); output.distance = Vec2.distance(output.pointA, output.pointB); output.iterations = iter; // Cache the simplex. simplex.writeCache(cache); // Apply radii if requested. if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > Math.EPSILON) { // Shapes are still no overlapped. // Move the witness points to the outer surface. output.distance -= rA + rB; var normal = Vec2.sub(output.pointB, output.pointA); normal.normalize(); output.pointA.addMul(rA, normal); output.pointB.subMul(rB, normal); } else { // Shapes are overlapped when radii are considered. // Move the witness points to the middle. var p = Vec2.mid(output.pointA, output.pointB); output.pointA.set(p); output.pointB.set(p); output.distance = 0; } } } /** * A distance proxy is used by the GJK algorithm. It encapsulates any shape. */ function DistanceProxy() { this.m_buffer = []; // Vec2[2] this.m_vertices = []; // Vec2[] this.m_count = 0; this.m_radius = 0; } /** * Get the vertex count. */ DistanceProxy.prototype.getVertexCount = function() { return this.m_count; }; /** * Get a vertex by index. Used by Distance. */ DistanceProxy.prototype.getVertex = function(index) { _ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; /** * Get the supporting vertex index in the given direction. */ 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; }; /** * Get the supporting vertex in the given direction. */ DistanceProxy.prototype.getSupportVertex = function(d) { return this.m_vertices[this.getSupport(d)]; }; /** * Initialize the proxy using the given shape. The shape must remain in scope * while the proxy is in use. */ DistanceProxy.prototype.set = function(shape, index) { // TODO remove, use shape instead _ASSERT && common.assert(typeof shape.computeDistanceProxy === "function"); shape.computeDistanceProxy(this, index); }; function SimplexVertex() { this.indexA; // wA index this.indexB; // wB index this.wA = Vec2.zero(); // support point in proxyA this.wB = Vec2.zero(); // support point in proxyB this.w = Vec2.zero(); // wB - wA 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; } }; // (SimplexCache, DistanceProxy, ...) Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) { _ASSERT && common.assert(cache.count <= 3); // Copy data from cache. this.m_count = cache.count; for (var i = 0; i < this.m_count; ++i) { var v = this.m_v[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.getVertex(v.indexA); var wBLocal = proxyB.getVertex(v.indexB); v.wA = Transform.mulVec2(transformA, wALocal); v.wB = Transform.mulVec2(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 0; } // Compute the new simplex metric, if it is substantially different than // old metric then flush the simplex. if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.getMetric(); if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) { // Reset the simplex. this.m_count = 0; } } // If the cache is empty or invalid... if (this.m_count == 0) { var v = this.m_v[0]; // SimplexVertex v.indexA = 0; v.indexB = 0; var wALocal = proxyA.getVertex(0); var wBLocal = proxyB.getVertex(0); v.wA = Transform.mulVec2(transformA, wALocal); v.wB = Transform.mulVec2(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 1; this.m_count = 1; } }; // (SimplexCache) 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) { // Origin is left of e12. return Vec2.cross(1, e12); } else { // Origin is right of e12. return Vec2.cross(e12, 1); } } default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getClosestPoint = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return Vec2.zero(); case 1: return Vec2.clone(this.m_v1.w); case 2: return Vec2.combine(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w); case 3: return Vec2.zero(); default: _ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: _ASSERT && common.assert(false); break; case 1: pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.setCombine(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: pA.setCombine(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.addMul(this.m_v3.a, this.m_v3.wA); pB.set(pA); break; default: _ASSERT && common.assert(false); break; } }; Simplex.prototype.getMetric = function() { switch (this.m_count) { case 0: _ASSERT && common.assert(false); return 0; case 1: return 0; case 2: return Vec2.distance(this.m_v1.w, this.m_v2.w); case 3: return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w)); default: _ASSERT && common.assert(false); return 0; } }; Simplex.prototype.solve = function() { switch (this.m_count) { case 1: break; case 2: this.solve2(); break; case 3: this.solve3(); break; default: _ASSERT && common.assert(false); } }; // Solve a line segment using barycentric coordinates. // // p = a1 * w1 + a2 * w2 // a1 + a2 = 1 // // The vector from the origin to the closest point on the line is // perpendicular to the line. // e12 = w2 - w1 // dot(p, e) = 0 // a1 * dot(w1, e) + a2 * dot(w2, e) = 0 // // 2-by-2 linear system // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // // Define // d12_1 = dot(w2, e12) // d12_2 = -dot(w1, e12) // d12 = d12_1 + d12_2 // // Solution // a1 = d12_1 / d12 // a2 = d12_2 / d12 Simplex.prototype.solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = Vec2.sub(w2, w1); // w1 region var d12_2 = -Vec2.dot(w1, e12); if (d12_2 <= 0) { // a2 <= 0, so we clamp it to 0 this.m_v1.a = 1; this.m_count = 1; return; } // w2 region var d12_1 = Vec2.dot(w2, e12); if (d12_1 <= 0) { // a1 <= 0, so we clamp it to 0 this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } // Must be in e12 region. 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; }; // Possible regions: // - points[2] // - edge points[0]-points[2] // - edge points[1]-points[2] // - inside the triangle Simplex.prototype.solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; // Edge12 // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // a3 = 0 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; // Edge13 // [1 1 ][a1] = [1] // [w1.e13 w3.e13][a3] = [0] // a2 = 0 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; // Edge23 // [1 1 ][a2] = [1] // [w2.e23 w3.e23][a3] = [0] // a1 = 0 var e23 = Vec2.sub(w3, w2); // Vec2 var w2e23 = Vec2.dot(w2, e23); var w3e23 = Vec2.dot(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; // Triangle123 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); // w1 region if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } // e12 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; } // e13 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; } // w2 region if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } // w3 region if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.set(this.m_v3); return; } // e23 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; } // Must be in triangle123 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; }; /** * Determine if two generic shapes overlap. */ Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = new DistanceInput(); input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; var cache = new SimplexCache(); var output = new DistanceOutput(); Distance(output, cache, input); return output.distance < 10 * Math.EPSILON; }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/common":50}],14:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Pool = require("../util/Pool"); var Vec2 = require("../common/Vec2"); var Math = require("../common/Math"); var AABB = require("./AABB"); module.exports = DynamicTree; /** * A node in the dynamic tree. The client does not interact with this directly. * * @prop {AABB} aabb Enlarged AABB * @prop {integer} height 0: leaf, -1: free node */ 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; }; /** * A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. A * dynamic tree arranges data in a binary tree to accelerate queries such as * volume queries and ray casts. Leafs are proxies with an AABB. In the tree we * expand the proxy AABB by `aabbExtension` so that the proxy AABB is bigger * than the client object. This allows the client object to move by small * amounts without triggering a tree update. * * Nodes are pooled and relocatable, so we use node indices rather than * pointers. */ function DynamicTree() { this.m_root = null; this.m_nodes = {}; this.m_lastProxyId = 0; this.m_pool = new Pool({ create: function() { return new TreeNode(); } }); } /** * Get proxy user data. * * @return the proxy user data or 0 if the id is invalid. */ DynamicTree.prototype.getUserData = function(id) { var node = this.m_nodes[id]; _ASSERT && common.assert(!!node); return node.userData; }; /** * Get the fat AABB for a node id. * * @return the proxy user data or 0 if the id is invalid. */ 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]; }; /** * Create a proxy in the tree as a leaf node. We return the index of the node * instead of a pointer so that we can grow the node pool. * * Create a proxy. Provide a tight fitting AABB and a userData pointer. */ DynamicTree.prototype.createProxy = function(aabb, userData) { _ASSERT && common.assert(AABB.isValid(aabb)); var node = this.allocateNode(); node.aabb.set(aabb); // Fatten the aabb. AABB.extend(node.aabb, Settings.aabbExtension); node.userData = userData; node.height = 0; this.insertLeaf(node); return node.id; }; /** * Destroy a proxy. This asserts if the id is invalid. */ 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); }; /** * Move a proxy with a swepted AABB. If the proxy has moved outside of its * fattened AABB, then the proxy is removed from the tree and re-inserted. * Otherwise the function returns immediately. * * @param id * @param aabb * @param {Vec2} d Displacement * * @return true if the proxy was re-inserted. */ 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); // Extend AABB. aabb = node.aabb; AABB.extend(aabb, Settings.aabbExtension); // Predict AABB displacement. // var d = Vec2.mul(Settings.aabbMultiplier, displacement); 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; } // Find the best sibling for this node 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(); // Cost of creating a new parent for this node and the new leaf var cost = 2 * combinedArea; // Minimum cost of pushing the leaf further down the tree var inheritanceCost = 2 * (combinedArea - area); // Cost of descending into child1 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; } // Cost of descending into child2 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; } // Descend according to the minimum cost. if (cost < cost1 && cost < cost2) { break; } // Descend if (cost1 < cost2) { index = child1; } else { index = child2; } } var sibling = index; // Create a new parent. 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) { // The sibling was not the root. if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { // The sibling was the root. newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } // Walk back up the tree fixing heights and AABBs 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) { // Destroy parent and connect sibling to grandParent. if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling.parent = grandParent; this.freeNode(parent); // Adjust ancestor bounds. 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); } }; /** * Perform a left or right rotation if node A is imbalanced. Returns the new * root index. */ 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; // Rotate C up if (balance > 1) { var F = C.child1; var G = C.child2; // Swap A and C C.child1 = A; C.parent = A.parent; A.parent = C; // A's old parent should point to C if (C.parent != null) { if (C.parent.child1 == iA) { C.parent.child1 = C; } else { C.parent.child2 = C; } } else { this.m_root = C; } // Rotate 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; } // Rotate B up if (balance < -1) { var D = B.child1; var E = B.child2; // Swap A and B B.child1 = A; B.parent = A.parent; A.parent = B; // A's old parent should point to B if (B.parent != null) { if (B.parent.child1 == A) { B.parent.child1 = B; } else { B.parent.child2 = B; } } else { this.m_root = B; } // Rotate 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; }; /** * Compute the height of the binary tree in O(N) time. Should not be called * often. */ DynamicTree.prototype.getHeight = function() { if (this.m_root == null) { return 0; } return this.m_root.height; }; /** * Get the ratio of the sum of the node areas to the root area. */ 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) { // Free node in pool continue; } totalArea += node.aabb.getPerimeter(); } iteratorPool.release(it); return totalArea / rootArea; }; /** * Compute the height of a sub-tree. */ DynamicTree.prototype.computeHeight = function(id) { var node; if (typeof id !== "undefined") { node = this.m_nodes[id]; } else { node = this.m_root; } // _ASSERT && common.assert(0 <= id && id < this.m_nodeCapacity); 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(0 <= child1 && child1 < this.m_nodeCapacity); // _ASSERT && common.assert(0 <= child2 && child2 < this.m_nodeCapacity); _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; } // _ASSERT && common.assert(0 <= child1 && child1 < this.m_nodeCapacity); // _ASSERT && common.assert(0 <= child2 && child2 < this.m_nodeCapacity); 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); }; // Validate this tree. For testing. DynamicTree.prototype.validate = function() { ValidateStructure(this.m_root); ValidateMetrics(this.m_root); _ASSERT && common.assert(this.getHeight() == this.computeHeight()); }; /** * Get the maximum balance of an node in the tree. The balance is the difference * in height of the two children of a node. */ 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; }; /** * Build an optimal tree. Very expensive. For testing. */ DynamicTree.prototype.rebuildBottomUp = function() { var nodes = []; var count = 0; // Build array of leaves. Free the rest. var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { // free node in pool 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(); }; /** * Shift the world origin. Useful for large worlds. The shift formula is: * position -= newOrigin * * @param newOrigin The new origin with respect to the old origin */ DynamicTree.prototype.shiftOrigin = function(newOrigin) { // Build array of leaves. Free the rest. var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { var aabb = node.aabb; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; aabb.upperBound.x -= newOrigin.x; aabb.upperBound.y -= newOrigin.y; } iteratorPool.release(it); }; /** * @function {DynamicTree~queryCallback} * * @param id Node id. */ /** * Query an AABB for overlapping proxies. The callback class is called for each * proxy that overlaps the supplied AABB. * * @param {DynamicTree~queryCallback} queryCallback */ 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); }; /** * Ray-cast against the proxies in the tree. This relies on the callback to * perform a exact ray-cast in the case were the proxy contains a shape. The * callback also performs the any collision filtering. This has performance * roughly equal to k * log(n), where k is the number of collisions and n is the * number of proxies in the tree. * * @param input The ray-cast input data. The ray extends from p1 to p1 + * maxFraction * (p2 - p1). * @param rayCastCallback A function that is called for each proxy that is hit by * the ray. */ DynamicTree.prototype.rayCast = function(input, rayCastCallback) { // TODO GC _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(); // v is perpendicular to the segment. var v = Vec2.cross(1, r); var abs_v = Vec2.abs(v); // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) var maxFraction = input.maxFraction; // Build a bounding box for the segment. var segmentAABB = new AABB(); var t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); var stack = stackPool.allocate(); var subInput = inputPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, segmentAABB) == false) { continue; } // Separating axis for segment (Gino, p80). // |dot(v, p1 - c)| > dot(|v|, h) 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) { // The client has terminated the ray cast. return; } if (value > 0) { // update segment bounding box. maxFraction = value; t = Vec2.combine(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); } } else { stack.push(node.child1); stack.push(node.child2); } } stackPool.release(stack); inputPool.release(subInput); }; var inputPool = new Pool({ create: function() { return {}; }, release: function(stack) {} }); var stackPool = new Pool({ create: function() { return []; }, release: function(stack) { stack.length = 0; } }); var iteratorPool = new Pool({ create: function() { return new Iterator(); }, release: function(iterator) { iterator.close(); } }); function Iterator() { var parents = []; var states = []; return { preorder: function(root) { parents.length = 0; parents.push(root); states.length = 0; states.push(0); return this; }, next: function() { while (parents.length > 0) { var i = parents.length - 1; var node = parents[i]; if (states[i] === 0) { states[i] = 1; return node; } if (states[i] === 1) { states[i] = 2; if (node.child1) { parents.push(node.child1); states.push(1); return node.child1; } } if (states[i] === 2) { states[i] = 3; if (node.child2) { parents.push(node.child2); states.push(1); return node.child2; } } parents.pop(); states.pop(); } }, close: function() { parents.length = 0; } }; } },{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":48,"../util/common":50,"./AABB":11}],15:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = TimeOfImpact; module.exports.Input = TOIInput; module.exports.Output = TOIOutput; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Distance = require("./Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; /** * Input parameters for TimeOfImpact. * * @prop {DistanceProxy} proxyA * @prop {DistanceProxy} proxyB * @prop {Sweep} sweepA * @prop {Sweep} sweepB * @prop tMax defines sweep interval [0, tMax] */ function TOIInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.sweepA = new Sweep(); this.sweepB = new Sweep(); this.tMax; } // TOIOutput State TOIOutput.e_unknown = 0; TOIOutput.e_failed = 1; TOIOutput.e_overlapped = 2; TOIOutput.e_touching = 3; TOIOutput.e_separated = 4; /** * Output parameters for TimeOfImpact. * * @prop state * @prop t */ 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; /** * Compute the upper bound on time before two shapes penetrate. Time is * represented as a fraction between [0,tMax]. This uses a swept separating axis * and may miss some intermediate, non-tunneling collision. If you change the * time interval, you should call this function again. * * Note: use Distance to compute the contact point and normal at the time of * impact. * * CCD via the local separating axis method. This seeks progression by computing * the largest time at which separation is maintained. */ function TimeOfImpact(output, input) { var timer = Timer.now(); ++stats.toiCalls; output.state = TOIOutput.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; // DistanceProxy var proxyB = input.proxyB; // DistanceProxy var sweepA = input.sweepA; // Sweep var sweepB = input.sweepB; // Sweep // Large rotations can make the root finder fail, so we normalize the // sweep angles. 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; // Prepare input for distance query. var cache = new SimplexCache(); var distanceInput = new DistanceInput(); distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.useRadii = false; // The outer loop progressively attempts to compute new separating axes. // This loop terminates when an axis is repeated (no progress is made). for (;;) { var xfA = Transform.identity(); var xfB = Transform.identity(); sweepA.getTransform(xfA, t1); sweepB.getTransform(xfB, t1); // Get the distance between shapes. We can also use the results // to get a separating axis. distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); // If the shapes are overlapped, we give up on continuous collision. if (distanceOutput.distance <= 0) { // Failure! output.state = TOIOutput.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { // Victory! output.state = TOIOutput.e_touching; output.t = t1; break; } // Initialize the separating axis. var fcn = new SeparationFunction(); fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); if (false) { // Dump the curve seen by the root finder var N = 100; var dx = 1 / N; var xs = []; // [ N + 1 ]; var fs = []; // [ N + 1 ]; 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; } } // Compute the TOI on the separating axis. We do this by successively // resolving the deepest point. This loop is bounded by the number of // vertices. var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { // Find the deepest point at t2. Store the witness point indices. var s2 = fcn.findMinSeparation(t2); var indexA = fcn.indexA; var indexB = fcn.indexB; // Is the final configuration separated? if (s2 > target + tolerance) { // Victory! output.state = TOIOutput.e_separated; output.t = tMax; done = true; break; } // Has the separation reached tolerance? if (s2 > target - tolerance) { // Advance the sweeps t1 = t2; break; } // Compute the initial separation of the witness points. var s1 = fcn.evaluate(t1); var indexA = fcn.indexA; var indexB = fcn.indexB; // Check for initial overlap. This might happen if the root finder // runs out of iterations. if (s1 < target - tolerance) { output.state = TOIOutput.e_failed; output.t = t1; done = true; break; } // Check for touching if (s1 <= target + tolerance) { // Victory! t1 should hold the TOI (could be 0.0). output.state = TOIOutput.e_touching; output.t = t1; done = true; break; } // Compute 1D root of: f(x) - target = 0 var rootIterCount = 0; var a1 = t1, a2 = t2; for (;;) { // Use a mix of the secant rule and bisection. var t; if (rootIterCount & 1) { // Secant rule to improve convergence. t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { // Bisection to guarantee progress. 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 holds a tentative value for t1 t2 = t; break; } // Ensure we continue to bracket the root. 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) { // Root finder got stuck. Semi-victory. 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; } // SeparationFunction Type 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; // Sweep this.m_sweepB; // Sweep this.m_type; this.m_localPoint = Vec2.zero(); this.m_axis = Vec2.zero(); } // TODO_ERIN might not need to return the separation /** * @param {SimplexCache} cache * @param {DistanceProxy} proxyA * @param {Sweep} sweepA * @param {DistanceProxy} proxyB * @param {Sweep} sweepB * @param {float} t1 */ SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; _ASSERT && common.assert(0 < count && count < 3); this.m_sweepA = sweepA; this.m_sweepB = sweepB; var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t1); this.m_sweepB.getTransform(xfB, t1); if (count == 1) { this.m_type = e_points; var localPointA = this.m_proxyA.getVertex(cache.indexA[0]); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointA = Transform.mulVec2(xfA, localPointA); var pointB = Transform.mulVec2(xfB, localPointB); this.m_axis.setCombine(1, pointB, -1, pointA); var s = this.m_axis.normalize(); return s; } else if (cache.indexA[0] == cache.indexA[1]) { // Two points on B and one on A. this.m_type = e_faceB; var localPointB1 = proxyB.getVertex(cache.indexB[0]); var localPointB2 = proxyB.getVertex(cache.indexB[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1); this.m_axis.normalize(); var normal = Rot.mulVec2(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mulVec2(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mulVec2(xfA, localPointA); var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } else { // Two points on A and one or two points on B. this.m_type = e_faceA; var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1); this.m_axis.normalize(); var normal = Rot.mulVec2(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mulVec2(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mulVec2(xfB, localPointB); var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } }; SeparationFunction.prototype.compute = function(find, t) { // It was findMinSeparation and evaluate var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t); this.m_sweepB.getTransform(xfB, t); switch (this.m_type) { case e_points: { if (find) { var axisA = Rot.mulTVec2(xfA.q, this.m_axis); var axisB = Rot.mulTVec2(xfB.q, Vec2.neg(this.m_axis)); this.indexA = this.m_proxyA.getSupport(axisA); this.indexB = this.m_proxyB.getSupport(axisB); } var localPointA = this.m_proxyA.getVertex(this.indexA); var localPointB = this.m_proxyB.getVertex(this.indexB); var pointA = Transform.mulVec2(xfA, localPointA); var pointB = Transform.mulVec2(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mulVec2(xfA.q, this.m_axis); var pointA = Transform.mulVec2(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulTVec2(xfB.q, Vec2.neg(normal)); this.indexA = -1; this.indexB = this.m_proxyB.getSupport(axisB); } var localPointB = this.m_proxyB.getVertex(this.indexB); var pointB = Transform.mulVec2(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mulVec2(xfB.q, this.m_axis); var pointB = Transform.mulVec2(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulTVec2(xfA.q, Vec2.neg(normal)); this.indexB = -1; this.indexA = this.m_proxyA.getSupport(axisA); } var localPointA = this.m_proxyA.getVertex(this.indexA); var pointA = Transform.mulVec2(xfA, localPointA); var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); return sep; } default: _ASSERT && common.assert(false); if (find) { this.indexA = -1; this.indexB = -1; } return 0; } }; SeparationFunction.prototype.findMinSeparation = function(t) { return this.compute(true, t); }; SeparationFunction.prototype.evaluate = function(t) { return this.compute(false, t); }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":49,"../util/common":50,"./Distance":13}],16:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat22; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); /** * A 2-by-2 matrix. Stored in column-major order. */ 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; }; /** * Solve A * x = b, where b is a column vector. This is more efficient than * computing the inverse in one-shot cases. */ 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; }; /** * Multiply a matrix times a vector. If a rotation matrix is provided, then this * transforms the vector from one frame to another. */ 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) { // Mat22 _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); } _ASSERT && common.assert(false); }; Mat22.mulVec2 = function(mx, v) { _ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); }; Mat22.mulMat22 = function(mx, v) { _ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); _ASSERT && common.assert(false); }; /** * Multiply a matrix transpose times a vector. If a rotation matrix is provided, * then this transforms the vector from one frame to another (inverse * transform). */ Mat22.mulT = function(mx, v) { if (v && "x" in v && "y" in v) { // Vec2 _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) { // Mat22 _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); } _ASSERT && common.assert(false); }; Mat22.mulTVec2 = function(mx, v) { _ASSERT && Mat22.assert(mx); _ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); }; Mat22.mulTMat22 = function(mx, v) { _ASSERT && Mat22.assert(mx); _ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); }; Mat22.abs = function(mx) { _ASSERT && Mat22.assert(mx); return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey)); }; Mat22.add = function(mx1, mx2) { _ASSERT && Mat22.assert(mx1); _ASSERT && Mat22.assert(mx2); return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey)); }; },{"../util/common":50,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat33; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Vec3 = require("./Vec3"); /** * A 3-by-3 matrix. Stored in column-major order. */ 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!"); } }; /** * Set this matrix to all zeros. */ Mat33.prototype.setZero = function() { this.ex.setZero(); this.ey.setZero(); this.ez.setZero(); return this; }; /** * Solve A * x = b, where b is a column vector. This is more efficient than * computing the inverse in one-shot cases. * * @param {Vec3} v * @returns {Vec3} */ 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; }; /** * Solve A * x = b, where b is a column vector. This is more efficient than * computing the inverse in one-shot cases. Solve only the upper 2-by-2 matrix * equation. * * @param {Vec2} v * * @returns {Vec2} */ 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; }; /** * Get the inverse of this matrix as a 2-by-2. Returns the zero matrix if * singular. * * @param {Mat33} M */ 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; }; /** * Get the symmetric inverse of this matrix as a 3-by-3. Returns the zero matrix * if singular. * * @param {Mat33} M */ 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); }; /** * Multiply a matrix times a vector. * * @param {Mat33} a * @param {Vec3|Vec2} b * * @returns {Vec3|Vec2} */ Mat33.mul = function(a, b) { _ASSERT && Mat33.assert(a); if (b && "z" in b && "y" in b && "x" in b) { _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); } else if (b && "y" in b && "x" in b) { _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); } _ASSERT && common.assert(false); }; Mat33.mulVec3 = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); }; Mat33.mulVec2 = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); }; Mat33.add = function(a, b) { _ASSERT && Mat33.assert(a); _ASSERT && Mat33.assert(b); return new Mat33(Vec3.add(a.ex + b.ex), Vec3.add(a.ey + b.ey), Vec3.add(a.ez + b.ez)); }; },{"../util/common":50,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var native = Math; var math = module.exports = create(native); math.EPSILON = 1e-9; // TODO /** * This function is used to ensure that a floating point number is not a NaN or * infinity. */ 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!"); } }; /** * TODO: This is a approximate yet fast inverse square-root. */ math.invSqrt = function(x) { // TODO return 1 / native.sqrt(x); }; /** * Next Largest Power of 2 Given a binary integer value x, the next largest * power of 2 can be computed by a SWAR algorithm that recursively "folds" the * upper bits into the lower bits. This process yields a bit vector with the * same most significant 1 as x, but all 1's below it. Adding 1 to that value * yields the next largest power of 2. For a 32-bit value: */ math.nextPowerOfTwo = function(x) { // TODO 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":50,"../util/create":51}],19:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Position; var Vec2 = require("./Vec2"); var Rot = require("./Rot"); /** * @prop {Vec2} c location * @prop {float} a angle */ function Position() { this.c = Vec2.zero(); this.a = 0; } Position.prototype.getTransform = function(xf, p) { xf.q.set(this.a); xf.p.set(Vec2.sub(this.c, Rot.mulVec2(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Rot; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Math = require("./Math"); // TODO merge with Transform /** * Initialize from an angle in radians. */ function Rot(angle) { if (!(this instanceof Rot)) { return new Rot(angle); } if (typeof angle === "number") { this.setAngle(angle); } else if (typeof angle === "object") { this.set(angle); } else { this.setIdentity(); } } Rot.neo = function(angle) { var obj = Object.create(Rot.prototype); obj.setAngle(angle); return obj; }; Rot.clone = function(rot) { _ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); obj.s = rot.s; obj.c = rot.c; return obj; }; Rot.identity = function() { var obj = Object.create(Rot.prototype); obj.s = 0; obj.c = 1; return obj; }; Rot.isValid = function(o) { return o && Math.isFinite(o.s) && Math.isFinite(o.c); }; Rot.assert = function(o) { if (!_ASSERT) return; if (!Rot.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Rot!"); } }; /** * Set to the identity rotation. */ 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); // TODO_ERIN optimize this.s = Math.sin(angle); this.c = Math.cos(angle); } }; /** * Set using an angle in radians. */ Rot.prototype.setAngle = function(angle) { _ASSERT && Math.assert(angle); // TODO_ERIN optimize this.s = Math.sin(angle); this.c = Math.cos(angle); }; /** * Get the angle in radians. */ Rot.prototype.getAngle = function() { return Math.atan2(this.s, this.c); }; /** * Get the x-axis. */ Rot.prototype.getXAxis = function() { return Vec2.neo(this.c, this.s); }; /** * Get the u-axis. */ Rot.prototype.getYAxis = function() { return Vec2.neo(-this.s, this.c); }; /** * Multiply two rotations: q * r * * @returns Rot * * Rotate a vector * * @returns Vec2 */ Rot.mul = function(rot, m) { _ASSERT && Rot.assert(rot); if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // s = qs * rc + qc * rs // c = qc * rc - qs * rs var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); } }; Rot.mulRot = function(rot, m) { _ASSERT && Rot.assert(rot); _ASSERT && Rot.assert(m); // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // s = qs * rc + qc * rs // c = qc * rc - qs * rs var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; }; Rot.mulVec2 = function(rot, m) { _ASSERT && Rot.assert(rot); _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); }; Rot.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); }; /** * Transpose multiply two rotations: qT * r * * @returns Rot * * Inverse rotate a vector * * @returns Vec2 */ Rot.mulT = function(rot, m) { if ("c" in m && "s" in m) { _ASSERT && Rot.assert(m); // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] // s = qc * rs - qs * rc // c = qc * rc + qs * rs var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); } }; Rot.mulTRot = function(rot, m) { _ASSERT && Rot.assert(m); // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] // s = qc * rs - qs * rc // c = qc * rc + qs * rs var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; }; Rot.mulTVec2 = function(rot, m) { _ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); }; },{"../util/common":50,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Sweep; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); var Transform = require("./Transform"); /** * This describes the motion of a body/shape for TOI computation. Shapes are * defined with respect to the body origin, which may not coincide with the * center of mass. However, to support dynamics we must interpolate the center * of mass position. * * @prop {Vec2} localCenter Local center of mass position * @prop {Vec2} c World center position * @prop {float} a World angle * @prop {float} alpha0 Fraction of the current time step in the range [0,1], c0 * and a0 are c and a at alpha0. */ function Sweep(c, a) { _ASSERT && common.assert(typeof c === "undefined"); _ASSERT && common.assert(typeof a === "undefined"); this.localCenter = Vec2.zero(); this.c = Vec2.zero(); this.a = 0; this.alpha0 = 0; this.c0 = Vec2.zero(); this.a0 = 0; } Sweep.prototype.setTransform = function(xf) { var c = Transform.mulVec2(xf, this.localCenter); this.c.set(c); this.c0.set(c); this.a = xf.q.getAngle(); this.a0 = xf.q.getAngle(); }; Sweep.prototype.setLocalCenter = function(localCenter, xf) { this.localCenter.set(localCenter); var c = Transform.mulVec2(xf, this.localCenter); this.c.set(c); this.c0.set(c); }; /** * Get the interpolated transform at a specific time. * * @param xf * @param beta A factor in [0,1], where 0 indicates alpha0 */ Sweep.prototype.getTransform = function(xf, beta) { beta = typeof beta === "undefined" ? 0 : beta; xf.q.setAngle((1 - beta) * this.a0 + beta * this.a); xf.p.setCombine(1 - beta, this.c0, beta, this.c); // shift to origin xf.p.sub(Rot.mulVec2(xf.q, this.localCenter)); }; /** * Advance the sweep forward, yielding a new initial state. * * @param {float} alpha The new initial time */ Sweep.prototype.advance = function(alpha) { _ASSERT && common.assert(this.alpha0 < 1); var beta = (alpha - this.alpha0) / (1 - this.alpha0); this.c0.setCombine(beta, this.c, 1 - beta, this.c0); this.a0 = beta * this.a + (1 - beta) * this.a0; this.alpha0 = alpha; }; Sweep.prototype.forward = function() { this.a0 = this.a; this.c0.set(this.c); }; /** * normalize the angles in radians to be between -pi and pi. */ 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":50,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Transform; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); // TODO merge with Rot /** * A transform contains translation and rotation. It is used to represent the * position and orientation of rigid frames. Initialize using a position vector * and a rotation. * * @prop {Vec2} position * @prop {Rot} rotation */ 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; }; /** * Set this to the identity transform. */ Transform.prototype.setIdentity = function() { this.p.setZero(); this.q.setIdentity(); }; /** * Set this based on the position and angle. */ Transform.prototype.set = function(a, b) { if (typeof b === "undefined") { this.p.set(a.p); this.q.set(a.q); } else { this.p.set(a); this.q.set(b); } }; Transform.isValid = function(o) { return o && Vec2.isValid(o.p) && Rot.isValid(o.q); }; Transform.assert = function(o) { if (!_ASSERT) return; if (!Transform.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Transform!"); } }; /** * @param {Transform} a * @param {Vec2} b * @returns {Vec2} * * @param {Transform} a * @param {Transform} b * @returns {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); // v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p // = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p var xf = Transform.identity(); xf.q = Rot.mulRot(a.q, b.q); xf.p = Vec2.add(Rot.mulVec2(a.q, b.p), a.p); return xf; } }; Transform.mulAll = function(a, b) { _ASSERT && Transform.assert(a); var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; }; Transform.mulVec2 = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); }; Transform.mulXf = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); // v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p // = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p var xf = Transform.identity(); xf.q = Rot.mulRot(a.q, b.q); xf.p = Vec2.add(Rot.mulVec2(a.q, b.p), a.p); return xf; }; /** * @param {Transform} a * @param {Vec2} b * @returns {Vec2} * * @param {Transform} a * @param {Transform} b * @returns {Transform} */ 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); // v2 = A.q' * (B.q * v1 + B.p - A.p) // = A.q' * B.q * v1 + A.q' * (B.p - A.p) var xf = Transform.identity(); xf.q.set(Rot.mulTRot(a.q, b.q)); xf.p.set(Rot.mulTVec2(a.q, Vec2.sub(b.p, a.p))); return xf; } }; Transform.mulTVec2 = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); }; Transform.mulTXf = function(a, b) { _ASSERT && Transform.assert(a); _ASSERT && Transform.assert(b); // v2 = A.q' * (B.q * v1 + B.p - A.p) // = A.q' * B.q * v1 + A.q' * (B.p - A.p) var xf = Transform.identity(); xf.q.set(Rot.mulTRot(a.q, b.q)); xf.p.set(Rot.mulTVec2(a.q, Vec2.sub(b.p, a.p))); return xf; }; },{"../util/common":50,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec2; var common = require("../util/common"); var Math = require("./Math"); function Vec2(x, y) { if (!(this instanceof Vec2)) { return new Vec2(x, y); } if (typeof x === "undefined") { this.x = 0; this.y = 0; } else if (typeof x === "object") { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y; } _ASSERT && Vec2.assert(this); } Vec2.zero = function() { var obj = Object.create(Vec2.prototype); obj.x = 0; obj.y = 0; return obj; }; Vec2.neo = function(x, y) { var obj = Object.create(Vec2.prototype); obj.x = x; obj.y = y; return obj; }; Vec2.clone = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(v.x, v.y); }; Vec2.prototype.toString = function() { return JSON.stringify(this); }; /** * Does this vector contain finite coordinates? */ Vec2.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y); }; Vec2.assert = function(o) { if (!_ASSERT) return; if (!Vec2.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec2!"); } }; Vec2.prototype.clone = function() { return Vec2.clone(this); }; /** * Set this vector to all zeros. * * @returns this */ Vec2.prototype.setZero = function() { this.x = 0; this.y = 0; return this; }; /** * Set this vector to some specified coordinates. * * @returns 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; }; /** * @deprecated Use setCombine or setMul */ Vec2.prototype.wSet = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.setCombine(a, v, b, w); } else { return this.setMul(a, v); } }; /** * Set linear combination of v and w: `a * v + b * w` */ Vec2.prototype.setCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; // `this` may be `w` this.x = x; this.y = y; return this; }; Vec2.prototype.setMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x = x; this.y = y; return this; }; /** * Add a vector to this vector. * * @returns this */ Vec2.prototype.add = function(w) { _ASSERT && Vec2.assert(w); this.x += w.x; this.y += w.y; return this; }; /** * @deprecated Use addCombine or addMul */ Vec2.prototype.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.addCombine(a, v, b, w); } else { return this.addMul(a, v); } }; /** * Add linear combination of v and w: `a * v + b * w` */ Vec2.prototype.addCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; // `this` may be `w` this.x += x; this.y += y; return this; }; Vec2.prototype.addMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x += x; this.y += y; return this; }; /** * @deprecated Use subCombine or subMul */ Vec2.prototype.wSub = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return this.subCombine(a, v, b, w); } else { return this.subMul(a, v); } }; /** * Subtract linear combination of v and w: `a * v + b * w` */ Vec2.prototype.subCombine = function(a, v, b, w) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); _ASSERT && Math.assert(b); _ASSERT && Vec2.assert(w); var x = a * v.x + b * w.x; var y = a * v.y + b * w.y; // `this` may be `w` this.x -= x; this.y -= y; return this; }; Vec2.prototype.subMul = function(a, v) { _ASSERT && Math.assert(a); _ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; this.x -= x; this.y -= y; return this; }; /** * Subtract a vector from this vector * * @returns this */ Vec2.prototype.sub = function(w) { _ASSERT && Vec2.assert(w); this.x -= w.x; this.y -= w.y; return this; }; /** * Multiply this vector by a scalar. * * @returns this */ Vec2.prototype.mul = function(m) { _ASSERT && Math.assert(m); this.x *= m; this.y *= m; return this; }; /** * Get the length of this vector (the norm). * * For performance, use this instead of lengthSquared (if possible). */ Vec2.prototype.length = function() { return Vec2.lengthOf(this); }; /** * Get the length squared. */ Vec2.prototype.lengthSquared = function() { return Vec2.lengthSquared(this); }; /** * Convert this vector into a unit vector. * * @returns old length */ 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; }; /** * Get the length of this vector (the norm). * * For performance, use this instead of lengthSquared (if possible). */ Vec2.lengthOf = function(v) { _ASSERT && Vec2.assert(v); return Math.sqrt(v.x * v.x + v.y * v.y); }; /** * Get the length squared. */ 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; }; /** * Get the skew vector such that dot(skew_vec, other) == cross(vec, other) */ Vec2.skew = function(v) { _ASSERT && Vec2.assert(v); return Vec2.neo(-v.y, v.x); }; /** * Perform the dot product on two vectors. */ Vec2.dot = function(v, w) { _ASSERT && Vec2.assert(v); _ASSERT && Vec2.assert(w); return v.x * w.x + v.y * w.y; }; /** * Perform the cross product on two vectors. In 2D this produces a scalar. * * Perform the cross product on a vector and a scalar. In 2D this produces a * vector. */ 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; } }; /** * Returns `a + (v x w)` */ 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); }; /** * @deprecated Use combine */ Vec2.wAdd = function(a, v, b, w) { if (typeof b !== "undefined" || typeof w !== "undefined") { return Vec2.combine(a, v, b, w); } else { return Vec2.mul(a, v); } }; Vec2.combine = function(a, v, b, w) { return Vec2.zero().setCombine(a, v, b, w); }; Vec2.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":50,"./Math":18}],24:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec3; var common = require("../util/common"); var Math = require("./Math"); function Vec3(x, y, z) { if (!(this instanceof Vec3)) { return new Vec3(x, y, z); } if (typeof x === "undefined") { this.x = 0, this.y = 0, this.z = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y, this.z = x.z; } else { this.x = x, this.y = y, this.z = z; } _ASSERT && Vec3.assert(this); } Vec3.neo = function(x, y, z) { var obj = Object.create(Vec3.prototype); obj.x = x; obj.y = y; obj.z = z; return obj; }; Vec3.clone = function(v) { _ASSERT && Vec3.assert(v); return Vec3.neo(v.x, v.y, v.z); }; Vec3.prototype.toString = function() { return JSON.stringify(this); }; /** * Does this vector contain finite coordinates? */ Vec3.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z); }; Vec3.assert = function(o) { if (!_ASSERT) return; if (!Vec3.isValid(o)) { _DEBUG && common.debug(o); throw new Error("Invalid Vec3!"); } }; Vec3.prototype.setZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; Vec3.prototype.set = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; Vec3.prototype.add = function(w) { this.x += w.x; this.y += w.y; this.z += w.z; return this; }; Vec3.prototype.sub = function(w) { this.x -= w.x; this.y -= w.y; this.z -= w.z; return this; }; Vec3.prototype.mul = function(m) { this.x *= m; this.y *= m; this.z *= m; return this; }; Vec3.areEqual = function(v, w) { _ASSERT && Vec3.assert(v); _ASSERT && Vec3.assert(w); return v == w || typeof v === "object" && v !== null && typeof w === "object" && w !== null && v.x === w.x && v.y === w.y && v.z === w.z; }; /** * Perform the dot product on two vectors. */ Vec3.dot = function(v, w) { return v.x * w.x + v.y * w.y + v.z * w.z; }; /** * Perform the cross product on two vectors. In 2D this produces a scalar. */ Vec3.cross = function(v, w) { return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x); }; Vec3.add = function(v, w) { return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z); }; Vec3.sub = function(v, w) { return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z); }; Vec3.mul = function(v, m) { return new Vec3(m * v.x, m * v.y, m * v.z); }; Vec3.prototype.neg = function() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; Vec3.neg = function(v) { return new Vec3(-v.x, -v.y, -v.z); }; },{"../util/common":50,"./Math":18}],25:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Velocity; var Vec2 = require("./Vec2"); /** * @prop {Vec2} v linear * @prop {float} w angular */ function Velocity() { this.v = Vec2.zero(); this.w = 0; } },{"./Vec2":23}],26:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.toString = function(newline) { newline = typeof newline === "string" ? newline : "\n"; var string = ""; for (var name in this) { if (typeof this[name] !== "function" && typeof this[name] !== "object") { string += name + ": " + this[name] + newline; } } return string; }; },{}],27:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = DistanceJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); DistanceJoint.TYPE = "distance-joint"; DistanceJoint._super = Joint; DistanceJoint.prototype = create(DistanceJoint._super.prototype); /** * @typedef {Object} DistanceJointDef * * Distance joint definition. This requires defining an anchor point on both * bodies and the non-zero length of the distance joint. The definition uses * local anchor points so that the initial configuration can violate the * constraint slightly. This helps when saving and loading a game. Warning: Do * not use a zero or short length. * * @prop {float} frequencyHz The mass-spring-damper frequency in Hertz. A value * of 0 disables softness. * @prop {float} dampingRatio The damping ratio. 0 = no damping, 1 = critical * damping. * * @prop {Vec2} def.localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} def.localAnchorB The local anchor point relative to bodyB's origin. * @prop {number} def.length Distance length. */ var DEFAULTS = { frequencyHz: 0, dampingRatio: 0 }; /** * A distance joint constrains two points on two bodies to remain at a fixed * distance from each other. You can view this as a massless, rigid rod. * * @param {DistanceJointDef} def * @param {Body} bodyA * @param {Body} bodyB * @param {Vec2} anchorA Anchor A in global coordination. * @param {Vec2} anchorB Anchor B in global coordination. */ function DistanceJoint(def, bodyA, bodyB, anchorA, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, bodyB, anchorA, anchorB); } // order of constructor arguments is changed in v0.2 if (bodyB && anchorA && "m_type" in anchorA && "x" in bodyB && "y" in bodyB) { var temp = bodyB; bodyB = anchorA; anchorA = temp; } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = DistanceJoint.TYPE; // Solver shared this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.zero(); this.m_length = Math.isFinite(def.length) ? def.length : Vec2.distance(bodyA.getWorldPoint(this.m_localAnchorA), bodyB.getWorldPoint(this.m_localAnchorB)); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = 0; this.m_gamma = 0; this.m_bias = 0; // Solver temp this.m_u; // Vec2 this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } /** * The local anchor point relative to bodyA's origin. */ DistanceJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ DistanceJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * Set/get the natural length. Manipulating the length can lead to non-physical * behavior when the frequency is zero. */ DistanceJoint.prototype.setLength = function(length) { this.m_length = length; }; DistanceJoint.prototype.getLength = function() { return this.m_length; }; DistanceJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; DistanceJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; DistanceJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; DistanceJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; DistanceJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; DistanceJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; DistanceJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; DistanceJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; DistanceJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA)); // Handle singularity. 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; // Compute the effective mass matrix. this.m_mass = invMass != 0 ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; // Frequency var omega = 2 * Math.PI * this.m_frequencyHz; // Damping coefficient var d = 2 * this.m_mass * this.m_dampingRatio * omega; // Spring stiffness var k = this.m_mass * omega * omega; // magic formulas 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) { // Scale the impulse to support a variable time step. this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; // Cdot = dot(u, v + cross(w, r)) var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solvePositionConstraints = function(step) { if (this.m_frequencyHz > 0) { // There is no position correction for soft distance constraints. return true; } var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var length = u.normalize(); var C = length - this.m_length; C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":51,"../util/options":52}],28:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = FrictionJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); FrictionJoint.TYPE = "friction-joint"; FrictionJoint._super = Joint; FrictionJoint.prototype = create(FrictionJoint._super.prototype); /** * @typedef {Object} FrictionJointDef * * Friction joint definition. * * @prop {float} maxForce The maximum friction force in N. * @prop {float} maxTorque The maximum friction torque in N-m. * * @prop {Vec2} localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} localAnchorB The local anchor point relative to bodyB's origin. */ var DEFAULTS = { maxForce: 0, maxTorque: 0 }; /** * Friction joint. This is used for top-down friction. It provides 2D * translational friction and angular friction. * * @param {FrictionJointDef} def * @param {Body} bodyA * @param {Body} bodyB * @param {Vec2} anchor Anchor in global coordination. */ function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = FrictionJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); // Solver shared this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; // Solver temp this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_linearMass; // Mat22 this.m_angularMass; } /** * The local anchor point relative to bodyA's origin. */ FrictionJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ FrictionJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * Set the maximum friction force in N. */ FrictionJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(Math.isFinite(force) && force >= 0); this.m_maxForce = force; }; /** * Get the maximum friction force in N. */ FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; /** * Set the maximum friction torque in N*m. */ FrictionJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(Math.isFinite(torque) && torque >= 0); this.m_maxTorque = torque; }; /** * Get the maximum friction torque in N*m. */ FrictionJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; FrictionJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; FrictionJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; FrictionJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; FrictionJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; FrictionJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); // Compute the effective mass matrix. this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] var mA = this.m_invMassA, mB = this.m_invMassB; // float var iA = this.m_invIA, iB = this.m_invIB; // float 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) { // Scale impulses to support a variable time step. this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; // float var iA = this.m_invIA, iB = this.m_invIB; // float var h = step.dt; // float // Solve angular friction { var Cdot = wB - wA; // float var impulse = -this.m_angularMass * Cdot; // float var oldImpulse = this.m_angularImpulse; // float var maxImpulse = h * this.m_maxTorque; // float this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA))); // Vec2 var impulse = Vec2.neg(Mat22.mulVec2(this.m_linearMass, Cdot)); // Vec2 var oldImpulse = this.m_linearImpulse; // Vec2 this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; // float if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.normalize(); this.m_linearImpulse.mul(maxImpulse); } impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":50,"../util/create":51,"../util/options":52}],29:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = GearJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var RevoluteJoint = require("./RevoluteJoint"); var PrismaticJoint = require("./PrismaticJoint"); GearJoint.TYPE = "gear-joint"; GearJoint._super = Joint; GearJoint.prototype = create(GearJoint._super.prototype); /** * @typedef {Object} GearJointDef * * Gear joint definition. * * @prop {float} ratio The gear ratio. See GearJoint for explanation. * * @prop {RevoluteJoint|PrismaticJoint} joint1 The first revolute/prismatic * joint attached to the gear joint. * @prop {PrismaticJoint|RevoluteJoint} joint2 The second prismatic/revolute * joint attached to the gear joint. */ var DEFAULTS = { ratio: 1 }; /** * A gear joint is used to connect two joints together. Either joint can be a * revolute or prismatic joint. You specify a gear ratio to bind the motions * together: coordinate1 + ratio * coordinate2 = constant * * The ratio can be negative or positive. If one joint is a revolute joint and * the other joint is a prismatic joint, then the ratio will have units of * length or units of 1/length. Warning: You have to manually destroy the gear * joint if joint1 or joint2 is destroyed. * * This definition requires two existing revolute or prismatic joints (any * combination will work). * * @param {GearJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) { if (!(this instanceof GearJoint)) { return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = GearJoint.TYPE; _ASSERT && common.assert(joint1.m_type === RevoluteJoint.TYPE || joint1.m_type === PrismaticJoint.TYPE); _ASSERT && common.assert(joint2.m_type === RevoluteJoint.TYPE || joint2.m_type === PrismaticJoint.TYPE); this.m_joint1 = joint1 ? joint1 : def.joint1; this.m_joint2 = joint2 ? joint2 : def.joint2; this.m_ratio = Math.isFinite(ratio) ? ratio : def.ratio; this.m_type1 = this.m_joint1.getType(); this.m_type2 = this.m_joint2.getType(); // joint1 connects body A to body C // joint2 connects body B to body D var coordinateA, coordinateB; // float // TODO_ERIN there might be some problem with the joint edges in Joint. this.m_bodyC = this.m_joint1.getBodyA(); this.m_bodyA = this.m_joint1.getBodyB(); // Get geometry of joint1 var xfA = this.m_bodyA.m_xf; var aA = this.m_bodyA.m_sweep.a; var xfC = this.m_bodyC.m_xf; var aC = this.m_bodyC.m_sweep.a; if (this.m_type1 === RevoluteJoint.TYPE) { var revolute = this.m_joint1; // RevoluteJoint this.m_localAnchorC = revolute.m_localAnchorA; this.m_localAnchorA = revolute.m_localAnchorB; this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC = Vec2.zero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { var prismatic = this.m_joint1; // PrismaticJoint this.m_localAnchorC = prismatic.m_localAnchorA; this.m_localAnchorA = prismatic.m_localAnchorB; this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC = prismatic.m_localXAxisA; var pC = this.m_localAnchorC; var pA = Rot.mulTVec2(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p))); coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC); } this.m_bodyD = this.m_joint2.getBodyA(); this.m_bodyB = this.m_joint2.getBodyB(); // Get geometry of joint2 var xfB = this.m_bodyB.m_xf; var aB = this.m_bodyB.m_sweep.a; var xfD = this.m_bodyD.m_xf; var aD = this.m_bodyD.m_sweep.a; if (this.m_type2 === RevoluteJoint.TYPE) { var revolute = this.m_joint2; // RevoluteJoint this.m_localAnchorD = revolute.m_localAnchorA; this.m_localAnchorB = revolute.m_localAnchorB; this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD = Vec2.zero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { var prismatic = this.m_joint2; // PrismaticJoint this.m_localAnchorD = prismatic.m_localAnchorA; this.m_localAnchorB = prismatic.m_localAnchorB; this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD = prismatic.m_localXAxisA; var pD = this.m_localAnchorD; var pB = Rot.mulTVec2(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; // Solver temp this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD; // Vec2 this.m_mA, this.m_mB, this.m_mC, this.m_mD; // float this.m_iA, this.m_iB, this.m_iC, this.m_iD; // float this.m_JvAC, this.m_JvBD; // Vec2 this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD; // float this.m_mass; } /** * Get the first joint. */ GearJoint.prototype.getJoint1 = function() { return this.m_joint1; }; /** * Get the second joint. */ GearJoint.prototype.getJoint2 = function() { return this.m_joint2; }; /** * Set/Get the gear ratio. */ GearJoint.prototype.setRatio = function(ratio) { _ASSERT && common.assert(Math.isFinite(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.getRatio = function() { return this.m_ratio; }; GearJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; GearJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; GearJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_JvAC).mul(inv_dt); }; GearJoint.prototype.getReactionTorque = function(inv_dt) { var L = this.m_impulse * this.m_JwA; // float return inv_dt * L; }; GearJoint.prototype.initVelocityConstraints = function(step) { this.m_lcA = this.m_bodyA.m_sweep.localCenter; this.m_lcB = this.m_bodyB.m_sweep.localCenter; this.m_lcC = this.m_bodyC.m_sweep.localCenter; this.m_lcD = this.m_bodyD.m_sweep.localCenter; this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var aC = this.m_bodyC.c_position.a; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var aD = this.m_bodyD.c_position.a; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); this.m_mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { this.m_JvAC = Vec2.zero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = Rot.mulVec2(qC, this.m_localAxisC); // Vec2 var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); // Vec2 var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); // Vec2 this.m_JvAC = u; this.m_JwC = Vec2.cross(rC, u); this.m_JwA = Vec2.cross(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_type2 == RevoluteJoint.TYPE) { this.m_JvBD = Vec2.zero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = Rot.mulVec2(qD, this.m_localAxisD); // Vec2 var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); // Vec2 var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); // Vec2 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; } // Compute effective mass. this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (step.warmStarting) { vA.addMul(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.addMul(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.subMul(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.subMul(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD); // float Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; // float this.m_impulse += impulse; vA.addMul(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.addMul(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.subMul(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.subMul(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var cC = this.m_bodyC.c_position.c; var aC = this.m_bodyC.c_position.a; var cD = this.m_bodyD.c_position.c; var aD = this.m_bodyD.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); var linearError = 0; // float var coordinateA, coordinateB; // float var JvAC, JvBD; // Vec2 var JwA, JwB, JwC, JwD; // float var mass = 0; // float if (this.m_type1 == RevoluteJoint.TYPE) { JvAC = Vec2.zero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = Rot.mulVec2(qC, this.m_localAxisC); // Vec2 var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); // Vec2 var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); // Vec2 JvAC = u; JwC = Vec2.cross(rC, u); JwA = Vec2.cross(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = Vec2.sub(this.m_localAnchorC, this.m_lcC); // Vec2 var pA = Rot.mulTVec2(qC, Vec2.add(rA, Vec2.sub(cA, cC))); // Vec2 coordinateA = Vec2.dot(Vec2.sub(pA, pC), this.m_localAxisC); } if (this.m_type2 == RevoluteJoint.TYPE) { JvBD = Vec2.zero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = Rot.mulVec2(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); JvBD = Vec2.mul(this.m_ratio, u); JwD = this.m_ratio * Vec2.cross(rD, u); JwB = this.m_ratio * Vec2.cross(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD); // Vec2 var pB = Rot.mulTVec2(qD, Vec2.add(rB, Vec2.sub(cB, cD))); // Vec2 coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; // float var impulse = 0; // float if (mass > 0) { impulse = -C / mass; } cA.addMul(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.addMul(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.subMul(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.subMul(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; this.m_bodyC.c_position.c.set(cC); this.m_bodyC.c_position.a = aC; this.m_bodyD.c_position.c.set(cD); this.m_bodyD.c_position.a = aD; // TODO_ERIN not implemented 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":50,"../util/create":51,"../util/options":52,"./PrismaticJoint":32,"./RevoluteJoint":34}],30:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MotorJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MotorJoint.TYPE = "motor-joint"; MotorJoint._super = Joint; MotorJoint.prototype = create(MotorJoint._super.prototype); /** * @typedef {Object} MotorJointDef * * Motor joint definition. * * @prop {float} angularOffset The bodyB angle minus bodyA angle in radians. * @prop {float} maxForce The maximum motor force in N. * @prop {float} maxTorque The maximum motor torque in N-m. * @prop {float} correctionFactor Position correction factor in the range [0,1]. * @prop {Vec2} linearOffset Position of bodyB minus the position of bodyA, in * bodyA's frame, in meters. */ var DEFAULTS = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; /** * A motor joint is used to control the relative motion between two bodies. A * typical usage is to control the movement of a dynamic body with respect to * the ground. * * @param {MotorJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = MotorJoint.TYPE; this.m_linearOffset = def.linearOffset ? def.linearOffset : bodyA.getLocalPoint(bodyB.getPosition()); var angleA = bodyA.getAngle(); var angleB = bodyB.getAngle(); this.m_angularOffset = angleB - angleA; this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_correctionFactor = def.correctionFactor; // Solver temp this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_linearError; // Vec2 this.m_angularError; // float this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_linearMass; // Mat22 this.m_angularMass; } /** * Set the maximum friction force in N. */ MotorJoint.prototype.setMaxForce = function(force) { _ASSERT && common.assert(Math.isFinite(force) && force >= 0); this.m_maxForce = force; }; /** * Get the maximum friction force in N. */ MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; /** * Set the maximum friction torque in N*m. */ MotorJoint.prototype.setMaxTorque = function(torque) { _ASSERT && common.assert(Math.isFinite(torque) && torque >= 0); this.m_maxTorque = torque; }; /** * Get the maximum friction torque in N*m. */ MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; /** * Set the position correction factor in the range [0,1]. */ MotorJoint.prototype.setCorrectionFactor = function(factor) { _ASSERT && common.assert(Math.isFinite(factor) && 0 <= factor && factor <= 1); this.m_correctionFactor = factor; }; /** * Get the position correction factor in the range [0,1]. */ MotorJoint.prototype.getCorrectionFactor = function() { return this.m_correctionFactor; }; /** * Set/get the target linear offset, in frame A, in meters. */ 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; }; /** * Set/get the target angular offset, in radians. */ MotorJoint.prototype.setAngularOffset = function(angularOffset) { if (angularOffset != this.m_angularOffset) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_angularOffset = angularOffset; } }; MotorJoint.prototype.getAngularOffset = function() { return this.m_angularOffset; }; MotorJoint.prototype.getAnchorA = function() { return this.m_bodyA.getPosition(); }; MotorJoint.prototype.getAnchorB = function() { return this.m_bodyB.getPosition(); }; MotorJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_linearImpulse); }; MotorJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; MotorJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); // Compute the effective mass matrix. this.m_rA = Rot.mulVec2(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.neg(this.m_localCenterB)); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } this.m_linearError = Vec2.zero(); this.m_linearError.addCombine(1, cB, 1, this.m_rB); this.m_linearError.subCombine(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mulVec2(qA, this.m_linearOffset)); this.m_angularError = aB - aA - this.m_angularOffset; if (step.warmStarting) { // Scale impulses to support a variable time step. this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; var inv_h = step.inv_dt; // Solve angular friction { 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; } // Solve linear friction { var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.addMul(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mulVec2(this.m_linearMass, Cdot)); var oldImpulse = Vec2.clone(this.m_linearImpulse); this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; this.m_linearImpulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":50,"../util/create":51,"../util/options":52}],31:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MouseJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MouseJoint.TYPE = "mouse-joint"; MouseJoint._super = Joint; MouseJoint.prototype = create(MouseJoint._super.prototype); /** * @typedef {Object} MouseJointDef * * Mouse joint definition. This requires a world target point, tuning * parameters, and the time step. * * @prop [maxForce = 0.0] The maximum constraint force that can be exerted to * move the candidate body. Usually you will express as some multiple of * the weight (multiplier * mass * gravity). * @prop [frequencyHz = 5.0] The response speed. * @prop [dampingRatio = 0.7] The damping ratio. 0 = no damping, 1 = critical * damping. * * @prop {Vec2} target The initial world target point. This is assumed to * coincide with the body anchor initially. */ var DEFAULTS = { maxForce: 0, frequencyHz: 5, dampingRatio: .7 }; /** * A mouse joint is used to make a point on a body track a specified world * point. This a soft constraint with a maximum force. This allows the * constraint to stretch and without applying huge forces. * * NOTE: this joint is not documented in the manual because it was developed to * be used in the testbed. If you want to learn how to use the mouse joint, look * at the testbed. * * @param {MouseJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function MouseJoint(def, bodyA, bodyB, target) { if (!(this instanceof MouseJoint)) { return new MouseJoint(def, bodyA, bodyB, target); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = MouseJoint.TYPE; _ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0); _ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0); _ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0); this.m_targetA = target ? Vec2.clone(target) : def.target || Vec2.zero(); this.m_localAnchorB = Transform.mulTVec2(bodyB.getTransform(), this.m_targetA); this.m_maxForce = def.maxForce; this.m_impulse = Vec2.zero(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_beta = 0; this.m_gamma = 0; // Solver temp 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(); } /** * Use this to update the target point. */ 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; }; /** * Set/get the maximum force in Newtons. */ MouseJoint.prototype.setMaxForce = function(force) { this.m_maxForce = force; }; MouseJoint.getMaxForce = function() { return this.m_maxForce; }; /** * Set/get the frequency in Hertz. */ MouseJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; MouseJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; /** * Set/get the damping ratio (dimensionless). */ 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(); // Frequency var omega = 2 * Math.PI * this.m_frequencyHz; // Damping coefficient var d = 2 * mass * this.m_dampingRatio * omega; // Spring stiffness var k = mass * (omega * omega); // magic formulas // gamma has units of inverse mass. // beta has units of inverse time. 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; // Compute the effective mass matrix. this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * // invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y // -r1.x*r1.y] // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] var K = new Mat22(); K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; this.m_mass = K.getInverse(); this.m_C.set(cB); this.m_C.addCombine(1, this.m_rB, -1, this.m_targetA); this.m_C.mul(this.m_beta); // Cheat with some damping wB *= .98; if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); vB.addMul(this.m_invMassB, this.m_impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse); } else { this.m_impulse.setZero(); } velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solveVelocityConstraints = function(step) { var velocity = this.m_bodyB.c_velocity; var vB = Vec2.clone(velocity.v); var wB = velocity.w; // Cdot = v + cross(w, r) var Cdot = Vec2.cross(wB, this.m_rB); Cdot.add(vB); Cdot.addCombine(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mulVec2(this.m_mass, Cdot); var oldImpulse = Vec2.clone(this.m_impulse); this.m_impulse.add(impulse); var maxImpulse = step.dt * this.m_maxForce; this.m_impulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_impulse, oldImpulse); vB.addMul(this.m_invMassB, impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, impulse); velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":50,"../util/create":51,"../util/options":52}],32:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PrismaticJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; PrismaticJoint.TYPE = "prismatic-joint"; PrismaticJoint._super = Joint; PrismaticJoint.prototype = create(PrismaticJoint._super.prototype); /** * @typedef {Object} PrismaticJointDef * * Prismatic joint definition. This requires defining a line of motion using an * axis and an anchor point. The definition uses local anchor points and a local * axis so that the initial configuration can violate the constraint slightly. * The joint translation is zero when the local anchor points coincide in world * space. Using local anchors and a local axis helps when saving and loading a * game. * * @prop {boolean} enableLimit Enable/disable the joint limit. * @prop {float} lowerTranslation The lower translation limit, usually in * meters. * @prop {float} upperTranslation The upper translation limit, usually in * meters. * @prop {boolean} enableMotor Enable/disable the joint motor. * @prop {float} maxMotorForce The maximum motor torque, usually in N-m. * @prop {float} motorSpeed The desired motor speed in radians per second. * * @prop {Vec2} localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} localAnchorB The local anchor point relative to bodyB's origin. * @prop {Vec2} localAxisA The local translation unit axis in bodyA. * @prop {float} referenceAngle The constrained angle between the bodies: * bodyB_angle - bodyA_angle. */ var DEFAULTS = { enableLimit: false, lowerTranslation: 0, upperTranslation: 0, enableMotor: false, maxMotorForce: 0, motorSpeed: 0 }; /** * A prismatic joint. This joint provides one degree of freedom: translation * along an axis fixed in bodyA. Relative rotation is prevented. You can use a * joint limit to restrict the range of motion and a joint motor to drive the * motion or to model joint friction. * * @param {PrismaticJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function PrismaticJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof PrismaticJoint)) { return new PrismaticJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_localXAxisA = axis ? bodyA.getLocalVector(axis) : def.localAxisA || Vec2.neo(1, 0); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_lowerTranslation = def.lowerTranslation; this.m_upperTranslation = def.upperTranslation; this.m_maxMotorForce = def.maxMotorForce; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_limitState = inactiveLimit; this.m_axis = Vec2.zero(); this.m_perp = Vec2.zero(); // Solver temp this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_axis, this.m_perp; // Vec2 this.m_s1, this.m_s2; // float this.m_a1, this.m_a2; // float this.m_K = new Mat33(); this.m_motorMass; } /** * The local anchor point relative to bodyA's origin. */ PrismaticJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ PrismaticJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * The local joint axis relative to bodyA. */ PrismaticJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; /** * Get the reference angle. */ PrismaticJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; /** * Get the current joint translation, usually in meters. */ 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; }; /** * Get the current joint translation speed, usually in meters per second. */ PrismaticJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var rA = Rot.mulVec2(bA.m_xf.q, Vec2.sub(this.m_localAnchorA, bA.m_sweep.localCenter)); // Vec2 var rB = Rot.mulVec2(bB.m_xf.q, Vec2.sub(this.m_localAnchorB, bB.m_sweep.localCenter)); // Vec2 var p1 = Vec2.add(bA.m_sweep.c, rA); // Vec2 var p2 = Vec2.add(bB.m_sweep.c, rB); // Vec2 var d = Vec2.sub(p2, p1); // Vec2 var axis = Rot.mulVec2(bA.m_xf.q, this.m_localXAxisA); // Vec2 var vA = bA.m_linearVelocity; // Vec2 var vB = bB.m_linearVelocity; // Vec2 var wA = bA.m_angularVelocity; // float var wB = bB.m_angularVelocity; // float var speed = Vec2.dot(d, Vec2.cross(wA, axis)) + Vec2.dot(axis, Vec2.sub(Vec2.addCross(vB, wB, rB), Vec2.addCross(vA, wA, rA))); // float return speed; }; /** * Is the joint limit enabled? */ PrismaticJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; /** * Enable/disable the joint limit. */ 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; } }; /** * Get the lower joint limit, usually in meters. */ PrismaticJoint.prototype.getLowerLimit = function() { return this.m_lowerTranslation; }; /** * Get the upper joint limit, usually in meters. */ PrismaticJoint.prototype.getUpperLimit = function() { return this.m_upperTranslation; }; /** * Set the joint limits, usually in meters. */ 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; } }; /** * Is the joint motor enabled? */ PrismaticJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; /** * Enable/disable the joint motor. */ PrismaticJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; /** * Set the motor speed, usually in meters per second. */ PrismaticJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; /** * Set the maximum motor force, usually in N. */ PrismaticJoint.prototype.setMaxMotorForce = function(force) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorForce = force; }; /** * Get the motor speed, usually in meters per second. */ PrismaticJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; /** * Get the current motor force given the inverse time step, usually in N. */ PrismaticJoint.prototype.getMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; PrismaticJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PrismaticJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PrismaticJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis).mul(inv_dt); }; PrismaticJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; PrismaticJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); // Compute the effective masses. var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; // Compute motor Jacobian and effective mass. { this.m_axis = Rot.mulVec2(qA, this.m_localXAxisA); this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis); this.m_a2 = Vec2.cross(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } // Prismatic constraint. { this.m_perp = Rot.mulVec2(qA, this.m_localYAxisA); this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp); this.m_s2 = Vec2.cross(rB, this.m_perp); var s1test = Vec2.cross(rA, this.m_perp); var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; var k12 = iA * this.m_s1 + iB * this.m_s2; var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; var k22 = iA + iB; if (k22 == 0) { // For bodies with fixed rotation. 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); } // Compute motor and limit terms. if (this.m_enableLimit) { var jointTranslation = Vec2.dot(this.m_axis, d); // float 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) { // Account for variable time step. this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; // Solve linear motor constraint. if (this.m_enableMotor && this.m_limitState != equalLimits) { var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorForce; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = Vec2.mul(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } var Cdot1 = Vec2.zero(); Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB; Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA; Cdot1.y = wB - wA; if (this.m_enableLimit && this.m_limitState != inactiveLimit) { // Solve prismatic and limit constraint in block form. 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)); // Vec3 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); } // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + // f1(1:2) var b = Vec2.combine(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y)); // Vec2 var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y)); // Vec2 this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df = Vec3.sub(this.m_impulse, f1); var P = Vec2.combine(df.x, this.m_perp, df.z, this.m_axis); // Vec2 var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1; // float var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2; // float vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } else { // Limit is inactive, just solve the prismatic constraint in block form. var df = this.m_K.solve22(Vec2.neg(Cdot1)); // Vec2 this.m_impulse.x += df.x; this.m_impulse.y += df.y; var P = Vec2.mul(df.x, this.m_perp); // Vec2 var LA = df.x * this.m_s1 + df.y; // float var LB = df.x * this.m_s2 + df.y; // float vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; // Compute fresh Jacobians var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); // Vec2 var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // Vec2 var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); // Vec2 var axis = Rot.mulVec2(qA, this.m_localXAxisA); // Vec2 var a1 = Vec2.cross(Vec2.add(d, rA), axis); // float var a2 = Vec2.cross(rB, axis); // float var perp = Rot.mulVec2(qA, this.m_localYAxisA); // Vec2 var s1 = Vec2.cross(Vec2.add(d, rA), perp); // float var s2 = Vec2.cross(rB, perp); // float var impulse = Vec3(); var C1 = Vec2.zero(); // Vec2 C1.x = Vec2.dot(perp, d); C1.y = aB - aA - this.m_referenceAngle; var linearError = Math.abs(C1.x); // float var angularError = Math.abs(C1.y); // float var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var active = false; // bool var C2 = 0; // float if (this.m_enableLimit) { var translation = Vec2.dot(axis, d); // float if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) { // Prevent large angular corrections C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection); linearError = Math.max(linearError, Math.abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { // Prevent large linear corrections and allow some slop. 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) { // Prevent large linear corrections and allow some slop. 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; // float var k12 = iA * s1 + iB * s2; // float var k13 = iA * s1 * a1 + iB * s2 * a2; // float var k22 = iA + iB; // float if (k22 == 0) { // For fixed rotation k22 = 1; } var k23 = iA * a1 + iB * a2; // float var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; // float 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; // float var k12 = iA * s1 + iB * s2; // float var k22 = iA + iB; // float 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)); // Vec2 impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = Vec2.combine(impulse.x, perp, impulse.z, axis); // Vec2 var LA = impulse.x * s1 + impulse.y + impulse.z * a1; // float var LB = impulse.x * s2 + impulse.y + impulse.z * a2; // float cA.subMul(mA, P); aA -= iA * LA; cB.addMul(mB, P); aB += iB * LB; this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":50,"../util/create":51,"../util/options":52}],33:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PulleyJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); PulleyJoint.TYPE = "pulley-joint"; PulleyJoint.MIN_PULLEY_LENGTH = 2; // minPulleyLength PulleyJoint._super = Joint; PulleyJoint.prototype = create(PulleyJoint._super.prototype); /** * @typedef {Object} PulleyJointDef * * Pulley joint definition. This requires two ground anchors, two dynamic body * anchor points, and a pulley ratio. * * @prop {Vec2} groundAnchorA The first ground anchor in world coordinates. * This point never moves. * @prop {Vec2} groundAnchorB The second ground anchor in world coordinates. * This point never moves. * @prop {Vec2} localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} localAnchorB The local anchor point relative to bodyB's origin. * @prop {float} ratio The pulley ratio, used to simulate a block-and-tackle. * @prop {float} lengthA The reference length for the segment attached to bodyA. * @prop {float} lengthB The reference length for the segment attached to bodyB. */ var PulleyJointDef = { collideConnected: true }; /** * The pulley joint is connected to two bodies and two fixed ground points. The * pulley supports a ratio such that: length1 + ratio * length2 <= constant * * Yes, the force transmitted is scaled by the ratio. * * Warning: the pulley joint can get a bit squirrelly by itself. They often work * better when combined with prismatic joints. You should also cover the the * anchor points with static shapes to prevent one side from going to zero * length. * * @param {PulleyJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) { if (!(this instanceof PulleyJoint)) { return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio); } def = options(def, PulleyJointDef); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA ? groundA : def.groundAnchorA || Vec2.neo(-1, 1); this.m_groundAnchorB = groundB ? groundB : def.groundAnchorB || Vec2.neo(1, 1); this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.neo(-1, 0); this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.neo(1, 0); this.m_lengthA = Math.isFinite(def.lengthA) ? def.lengthA : Vec2.distance(anchorA, groundA); this.m_lengthB = Math.isFinite(def.lengthB) ? def.lengthB : Vec2.distance(anchorB, groundB); this.m_ratio = Math.isFinite(ratio) ? ratio : def.ratio; _ASSERT && common.assert(ratio > Math.EPSILON); this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB; this.m_impulse = 0; // Solver temp this.m_uA; // Vec2 this.m_uB; // Vec2 this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_mass; } /** * Get the first ground anchor. */ PulleyJoint.prototype.getGroundAnchorA = function() { return this.m_groundAnchorA; }; /** * Get the second ground anchor. */ PulleyJoint.prototype.getGroundAnchorB = function() { return this.m_groundAnchorB; }; /** * Get the current length of the segment attached to bodyA. */ PulleyJoint.prototype.getLengthA = function() { return this.m_lengthA; }; /** * Get the current length of the segment attached to bodyB. */ PulleyJoint.prototype.getLengthB = function() { return this.m_lengthB; }; /** * Get the pulley ratio. */ PulleyJoint.prototype.getRatio = function() { return this.m_ratio; }; /** * Get the current length of the segment attached to bodyA. */ PulleyJoint.prototype.getCurrentLengthA = function() { var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var s = this.m_groundAnchorA; return Vec2.distance(p, s); }; /** * Get the current length of the segment attached to bodyB. */ PulleyJoint.prototype.getCurrentLengthB = function() { var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var s = this.m_groundAnchorB; return Vec2.distance(p, s); }; PulleyJoint.prototype.shiftOrigin = function(newOrigin) { this.m_groundAnchorA.sub(newOrigin); this.m_groundAnchorB.sub(newOrigin); }; PulleyJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PulleyJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PulleyJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_uB).mul(inv_dt); }; PulleyJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; PulleyJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // Get the pulley axes. 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(); } // Compute effective mass. var ruA = Vec2.cross(this.m_rA, this.m_uA); // float var ruB = Vec2.cross(this.m_rB, this.m_uB); // float var mA = this.m_invMassA + this.m_invIA * ruA * ruA; // float var mB = this.m_invMassB + this.m_invIB * ruB * ruB; // float 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) { // Scale impulses to support variable time steps. this.m_impulse *= step.dtRatio; // Warm starting. var PA = Vec2.mul(-this.m_impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB); vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB); // float var impulse = -this.m_mass * Cdot; // float this.m_impulse += impulse; var PA = Vec2.mul(-impulse, this.m_uA); // Vec2 var PB = Vec2.mul(-this.m_ratio * impulse, this.m_uB); // Vec2 vA.addMul(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.addMul(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // Get the pulley axes. 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(); } // Compute effective mass. var ruA = Vec2.cross(rA, uA); var ruB = Vec2.cross(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; // float var mB = this.m_invMassB + this.m_invIB * ruB * ruB; // float var mass = mA + this.m_ratio * this.m_ratio * mB; // float if (mass > 0) { mass = 1 / mass; } var C = this.m_constant - lengthA - this.m_ratio * lengthB; // float var linearError = Math.abs(C); // float var impulse = -mass * C; // float var PA = Vec2.mul(-impulse, uA); // Vec2 var PB = Vec2.mul(-this.m_ratio * impulse, uB); // Vec2 cA.addMul(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.addMul(this.m_invMassB, PB); aB += this.m_invIB * Vec2.cross(rB, PB); this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":50,"../util/create":51,"../util/options":52}],34:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RevoluteJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RevoluteJoint.TYPE = "revolute-joint"; RevoluteJoint._super = Joint; RevoluteJoint.prototype = create(RevoluteJoint._super.prototype); /** * @typedef {Object} RevoluteJointDef * * Revolute joint definition. This requires defining an anchor point where the * bodies are joined. The definition uses local anchor points so that the * initial configuration can violate the constraint slightly. You also need to * specify the initial relative angle for joint limits. This helps when saving * and loading a game. * * The local anchor points are measured from the body's origin rather than the * center of mass because: 1. you might not know where the center of mass will * be. 2. if you add/remove shapes from a body and recompute the mass, the * joints will be broken. * * @prop {bool} enableLimit A flag to enable joint limits. * @prop {bool} enableMotor A flag to enable the joint motor. * @prop {float} lowerAngle The lower angle for the joint limit (radians). * @prop {float} upperAngle The upper angle for the joint limit (radians). * @prop {float} motorSpeed The desired motor speed. Usually in radians per * second. * @prop {float} maxMotorTorque The maximum motor torque used to achieve the * desired motor speed. Usually in N-m. * * @prop {Vec2} localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} localAnchorB The local anchor point relative to bodyB's origin. * @prop {float} referenceAngle The bodyB angle minus bodyA angle in the * reference state (radians). */ var DEFAULTS = { lowerAngle: 0, upperAngle: 0, maxMotorTorque: 0, motorSpeed: 0, enableLimit: false, enableMotor: false }; /** * A revolute joint constrains two bodies to share a common point while they are * free to rotate about the point. The relative rotation about the shared point * is the joint angle. You can limit the relative rotation with a joint limit * that specifies a lower and upper angle. You can use a motor to drive the * relative rotation about the shared point. A maximum motor torque is provided * so that infinite forces are not generated. * * @param {RevoluteJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function RevoluteJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RevoluteJoint)) { return new RevoluteJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorImpulse = 0; this.m_lowerAngle = def.lowerAngle; this.m_upperAngle = def.upperAngle; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; // Solver temp this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float // effective mass for point-to-point constraint. this.m_mass = new Mat33(); // effective mass for motor/limit angular constraint. this.m_motorMass; // float this.m_limitState = inactiveLimit; } /** * The local anchor point relative to bodyA's origin. */ RevoluteJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ RevoluteJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * Get the reference angle. */ RevoluteJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; /** * Get the current joint angle in radians. */ 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; }; /** * Get the current joint angle speed in radians per second. */ RevoluteJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_angularVelocity - bA.m_angularVelocity; }; /** * Is the joint motor enabled? */ RevoluteJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; /** * Enable/disable the joint motor. */ RevoluteJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; /** * Get the current motor torque given the inverse time step. Unit is N*m. */ RevoluteJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; /** * Set the motor speed in radians per second. */ RevoluteJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; /** * Get the motor speed in radians per second. */ RevoluteJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; /** * Set the maximum motor torque, usually in N-m. */ RevoluteJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; /** * Is the joint limit enabled? */ RevoluteJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; /** * Enable/disable the joint limit. */ 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; } }; /** * Get the lower joint limit in radians. */ RevoluteJoint.prototype.getLowerLimit = function() { return this.m_lowerAngle; }; /** * Get the upper joint limit in radians. */ RevoluteJoint.prototype.getUpperLimit = function() { return this.m_upperAngle; }; /** * Set the joint limits in radians. */ 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); }; /** * Get the reaction force given the inverse time step. Unit is N. */ RevoluteJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; /** * Get the reaction torque due to the joint limit given the inverse time step. * Unit is N*m. */ RevoluteJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; RevoluteJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float var fixedRotation = iA + iB === 0; // bool 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; // float 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) { // Scale impulses to support a variable time step. this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float var fixedRotation = iA + iB === 0; // bool // Solve motor constraint. if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) { var Cdot = wB - wA - this.m_motorSpeed; // float var impulse = -this.m_motorMass * Cdot; // float var oldImpulse = this.m_motorImpulse; // float var maxImpulse = step.dt * this.m_maxMotorTorque; // float this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve limit constraint. if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; // float var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(this.m_mass.solve33(Cdot)); // Vec3 if (this.m_limitState == equalLimits) { this.m_impulse.add(impulse); } else if (this.m_limitState == atLowerLimit) { var newImpulse = this.m_impulse.z + impulse.z; // float if (newImpulse < 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); // Vec2 var reduced = this.m_mass.solve22(rhs); // Vec2 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; // float if (newImpulse > 0) { var rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); // Vec2 var reduced = this.m_mass.solve22(rhs); // Vec2 impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { // Solve point-to-point constraint var Cdot = Vec2.zero(); Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse = this.m_mass.solve22(Vec2.neg(Cdot)); // Vec2 this.m_impulse.x += impulse.x; this.m_impulse.y += impulse.y; vA.subMul(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.addMul(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var angularError = 0; // float var positionError = 0; // float var fixedRotation = this.m_invIA + this.m_invIB == 0; // bool // Solve angular limit constraint. if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var angle = aB - aA - this.m_referenceAngle; // float var limitImpulse = 0; // float if (this.m_limitState == equalLimits) { // Prevent large angular corrections var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); // float limitImpulse = -this.m_motorMass * C; angularError = Math.abs(C); } else if (this.m_limitState == atLowerLimit) { var C = angle - this.m_lowerAngle; // float angularError = -C; // Prevent large angular corrections and allow some slop. 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; // float angularError = C; // Prevent large angular corrections and allow some slop. C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } // Solve point-to-point constraint. { qA.set(aA); qB.set(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); // Vec2 var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // Vec2 var C = Vec2.zero(); C.addCombine(1, cB, 1, rB); C.subCombine(1, cA, 1, rA); positionError = C.length(); var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float 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)); // Vec2 cA.subMul(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.addMul(mB, impulse); aB += iB * Vec2.cross(rB, impulse); } this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":50,"../util/create":51,"../util/options":52}],35:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RopeJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RopeJoint.TYPE = "rope-joint"; RopeJoint._super = Joint; RopeJoint.prototype = create(RopeJoint._super.prototype); /** * @typedef {Object} RopeJointDef * * Rope joint definition. This requires two body anchor points and a maximum * lengths. Note: by default the connected objects will not collide. see * collideConnected in JointDef. * * @prop {float} maxLength The maximum length of the rope. Warning: this must be * larger than linearSlop or the joint will have no effect. * * @prop {Vec2} def.localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} def.localAnchorB The local anchor point relative to bodyB's origin. */ var DEFAULTS = { maxLength: 0 }; /** * A rope joint enforces a maximum distance between two points on two bodies. It * has no other effect. * * Warning: if you attempt to change the maximum length during the simulation * you will get some non-physical behavior. * * A model that would allow you to dynamically modify the length would have some * sponginess, so I chose not to implement it that way. See DistanceJoint if you * want to dynamically control length. * * @param {RopeJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = RopeJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1, 0); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1, 0); this.m_maxLength = def.maxLength; this.m_mass = 0; this.m_impulse = 0; this.m_length = 0; this.m_state = inactiveLimit; // Solver temp this.m_u; // Vec2 this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_mass; } /** * The local anchor point relative to bodyA's origin. */ RopeJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ RopeJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * Set/Get the maximum length of the rope. */ RopeJoint.prototype.setMaxLength = function(length) { this.m_maxLength = length; }; RopeJoint.prototype.getMaxLength = function() { return this.m_maxLength; }; RopeJoint.prototype.getLimitState = function() { // TODO LimitState return this.m_state; }; RopeJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RopeJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RopeJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(this.m_impulse, this.m_u).mul(inv_dt); }; RopeJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; RopeJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); this.m_u = Vec2.zero(); this.m_u.addCombine(1, cB, 1, this.m_rB); this.m_u.subCombine(1, cA, 1, this.m_rA); // Vec2 this.m_length = this.m_u.length(); var C = this.m_length - this.m_maxLength; // float 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; } // Compute effective mass. var crA = Vec2.cross(this.m_rA, this.m_u); // float var crB = Vec2.cross(this.m_rB, this.m_u); // float var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; // float this.m_mass = invMass != 0 ? 1 / invMass : 0; if (step.warmStarting) { // Scale the impulse to support a variable time step. this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; // Cdot = dot(u, v + cross(w, r)) var vpA = Vec2.addCross(vA, wA, this.m_rA); // Vec2 var vpB = Vec2.addCross(vB, wB, this.m_rB); // Vec2 var C = this.m_length - this.m_maxLength; // float var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); // float // Predictive constraint. if (C < 0) { Cdot += step.inv_dt * C; } var impulse = -this.m_mass * Cdot; // float var oldImpulse = this.m_impulse; // float this.m_impulse = Math.min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = Vec2.mul(impulse, this.m_u); // Vec2 vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.addMul(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; // Vec2 var aA = this.m_bodyA.c_position.a; // float var cB = this.m_bodyB.c_position.c; // Vec2 var aB = this.m_bodyB.c_position.a; // float var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.zero(); u.addCombine(1, cB, 1, rB); u.subCombine(1, cA, 1, rA); // Vec2 var length = u.normalize(); // float var C = length - this.m_maxLength; // float C = Math.clamp(C, 0, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; // float var P = Vec2.mul(impulse, u); // Vec2 cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.addMul(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return length - this.m_maxLength < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":51,"../util/options":52}],36:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WeldJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WeldJoint.TYPE = "weld-joint"; WeldJoint._super = Joint; WeldJoint.prototype = create(WeldJoint._super.prototype); /** * @typedef {Object} WeldJointDef * * Weld joint definition. You need to specify local anchor points where they are * attached and the relative body angle. The position of the anchor points is * important for computing the reaction torque. * * @prop {float} frequencyHz The mass-spring-damper frequency in Hertz. Rotation * only. Disable softness with a value of 0. * @prop {float} dampingRatio The damping ratio. 0 = no damping, 1 = critical * damping. * * @prop {Vec2} localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} localAnchorB The local anchor point relative to bodyB's origin. * @prop {float} referenceAngle The bodyB angle minus bodyA angle in the * reference state (radians). */ var DEFAULTS = { frequencyHz: 0, dampingRatio: 0 }; /** * A weld joint essentially glues two bodies together. A weld joint may distort * somewhat because the island constraint solver is approximate. * * @param {WeldJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WeldJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = Vec3(); this.m_bias = 0; this.m_gamma = 0; // Solver temp this.m_rA; // Vec2 this.m_rB; // Vec2 this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_mass = new Mat33(); } /** * The local anchor point relative to bodyA's origin. */ WeldJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ WeldJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * Get the reference angle. */ WeldJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; /** * Set/get frequency in Hz. */ WeldJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; WeldJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; /** * Set/get damping ratio. */ WeldJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WeldJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; WeldJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WeldJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WeldJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt); }; WeldJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; WeldJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float 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; // float var m = invM > 0 ? 1 / invM : 0; // float var C = aB - aA - this.m_referenceAngle; // float // Frequency var omega = 2 * Math.PI * this.m_frequencyHz; // float // Damping coefficient var d = 2 * m * this.m_dampingRatio * omega; // float // Spring stiffness var k = m * omega * omega; // float // magic formulas var h = step.dt; // float 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) { // Scale impulses to support a variable time step. this.m_impulse.mul(step.dtRatio); var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; // float var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); // float this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); // Vec2 var impulse1 = Vec2.neg(Mat33.mulVec2(this.m_mass, Cdot1)); // Vec2 this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); // Vec2 vA.subMul(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA)); // Vec2 var Cdot2 = wB - wA; // float var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); // Vec3 var impulse = Vec3.neg(Mat33.mulVec3(this.m_mass, Cdot)); // Vec3 this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.subMul(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.addMul(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var mA = this.m_invMassA, mB = this.m_invMassB; // float var iA = this.m_invIA, iB = this.m_invIB; // float var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var positionError, angularError; // float var K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); // Vec2 positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); // Vec2 cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.addCombine(1, cB, 1, rB); C1.subCombine(1, cA, 1, rA); var C2 = aB - aA - this.m_referenceAngle; // float positionError = C1.length(); angularError = Math.abs(C2); var C = Vec3(C1.x, C1.y, C2); var impulse = Vec3(); if (K.ez.z > 0) { impulse = Vec3.neg(K.solve33(C)); } else { var impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0); } var P = Vec2.neo(impulse.x, impulse.y); cA.subMul(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.addMul(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":51,"../util/options":52}],37:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WheelJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WheelJoint.TYPE = "wheel-joint"; WheelJoint._super = Joint; WheelJoint.prototype = create(WheelJoint._super.prototype); /** * @typedef {Object} WheelJointDef * * Wheel joint definition. This requires defining a line of motion using an axis * and an anchor point. The definition uses local anchor points and a local axis * so that the initial configuration can violate the constraint slightly. The * joint translation is zero when the local anchor points coincide in world * space. Using local anchors and a local axis helps when saving and loading a * game. * * @prop {boolean} enableMotor Enable/disable the joint motor. * @prop {float} maxMotorTorque The maximum motor torque, usually in N-m. * @prop {float} motorSpeed The desired motor speed in radians per second. * @prop {float} frequencyHz Suspension frequency, zero indicates no suspension. * @prop {float} dampingRatio Suspension damping ratio, one indicates critical * damping. * * @prop {Vec2} localAnchorA The local anchor point relative to bodyA's origin. * @prop {Vec2} localAnchorB The local anchor point relative to bodyB's origin. * @prop {Vec2} localAxisA The local translation axis in bodyA. */ var DEFAULTS = { enableMotor: false, maxMotorTorque: 0, motorSpeed: 0, frequencyHz: 2, dampingRatio: .7 }; /** * A wheel joint. This joint provides two degrees of freedom: translation along * an axis fixed in bodyA and rotation in the plane. In other words, it is a * point to line constraint with a rotational motor and a linear spring/damper. * This joint is designed for vehicle suspensions. * * @param {WheelJointDef} def * @param {Body} bodyA * @param {Body} bodyB */ function WheelJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, DEFAULTS); Joint.call(this, def, bodyA, bodyB); bodyA = this.m_bodyA; bodyB = this.m_bodyB; this.m_type = WheelJoint.TYPE; this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero(); this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero(); this.m_localAxis = axis ? bodyA.getLocalVector(axis) : def.localAxisA || Vec2.neo(1, 0); this.m_localXAxisA = this.m_localAxis; this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_mass = 0; this.m_impulse = 0; this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_springMass = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0; this.m_gamma = 0; // Solver temp this.m_localCenterA; // Vec2 this.m_localCenterB; // Vec2 this.m_invMassA; // float this.m_invMassB; // float this.m_invIA; // float this.m_invIB; // float this.m_ax = Vec2.zero(); this.m_ay = Vec2.zero(); // Vec2 this.m_sAx; this.m_sBx; // float this.m_sAy; this.m_sBy; } /** * The local anchor point relative to bodyA's origin. */ WheelJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; /** * The local anchor point relative to bodyB's origin. */ WheelJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; /** * The local joint axis relative to bodyA. */ WheelJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; /** * Get the current joint translation, usually in meters. */ WheelJoint.prototype.getJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.getWorldPoint(this.m_localAnchorA); // Vec2 var pB = bB.getWorldPoint(this.m_localAnchorB); // Vec2 var d = Vec2.sub(pB, pA); // Vec2 var axis = bA.getWorldVector(this.m_localXAxisA); // Vec2 var translation = Vec2.dot(d, axis); // float return translation; }; /** * Get the current joint translation speed, usually in meters per second. */ WheelJoint.prototype.getJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; /** * Is the joint motor enabled? */ WheelJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; /** * Enable/disable the joint motor. */ WheelJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; /** * Set the motor speed, usually in radians per second. */ WheelJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; /** * Get the motor speed, usually in radians per second. */ WheelJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; /** * Set/Get the maximum motor force, usually in N-m. */ 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; }; /** * Get the current motor torque given the inverse time step, usually in N-m. */ WheelJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; /** * Set/Get the spring frequency in hertz. Setting the frequency to zero disables * the spring. */ WheelJoint.prototype.setSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; WheelJoint.prototype.getSpringFrequencyHz = function() { return this.m_frequencyHz; }; /** * Set/Get the spring damping ratio */ WheelJoint.prototype.setSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WheelJoint.prototype.getSpringDampingRatio = function() { return this.m_dampingRatio; }; WheelJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WheelJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WheelJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax).mul(inv_dt); }; WheelJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float 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); // Compute the effective masses. var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); // Vec2 // Point to line constraint { this.m_ay = Rot.mulVec2(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } // Spring constraint this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { this.m_ax = Rot.mulVec2(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; // float if (invMass > 0) { this.m_springMass = 1 / invMass; var C = Vec2.dot(d, this.m_ax); // float // Frequency var omega = 2 * Math.PI * this.m_frequencyHz; // float // Damping coefficient var d = 2 * this.m_springMass * this.m_dampingRatio * omega; // float // Spring stiffness var k = this.m_springMass * omega * omega; // float // magic formulas var h = step.dt; // float 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; } // Rotational motor 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) { // Account for variable time step. this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; var P = Vec2.combine(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.subMul(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.addMul(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solveVelocityConstraints = function(step) { var mA = this.m_invMassA; var mB = this.m_invMassB; // float var iA = this.m_invIA; var iB = this.m_invIB; // float 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; // Solve spring constraint { var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; // float var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); // float this.m_springImpulse += impulse; var P = Vec2.mul(impulse, this.m_ax); // Vec2 var LA = impulse * this.m_sAx; // float var LB = impulse * this.m_sBx; // float vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } // Solve rotational motor constraint { var Cdot = wB - wA - this.m_motorSpeed; // float var impulse = -this.m_motorMass * Cdot; // float var oldImpulse = this.m_motorImpulse; // float var maxImpulse = step.dt * this.m_maxMotorTorque; // float this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve point to line constraint { var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; // float var impulse = -this.m_mass * Cdot; // float this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_ay); // Vec2 var LA = impulse * this.m_sAy; // float var LB = impulse * this.m_sBy; // float vA.subMul(mA, P); wA -= iA * LA; vB.addMul(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.addCombine(1, cB, 1, rB); d.subCombine(1, cA, 1, rA); var ay = Rot.mulVec2(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.add(d, rA), ay); // float var sBy = Vec2.cross(rB, ay); // float var C = Vec2.dot(d, ay); // float 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; // float var impulse; // float if (k != 0) { impulse = -C / k; } else { impulse = 0; } var P = Vec2.mul(impulse, ay); // Vec2 var LA = impulse * sAy; // float var LB = impulse * sBy; // float cA.subMul(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.addMul(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":51,"../util/options":52}],38:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; var common = require("../util/common"); var create = require("../util/create"); var PolygonShape = require("./PolygonShape"); BoxShape._super = PolygonShape; BoxShape.prototype = create(BoxShape._super.prototype); BoxShape.TYPE = "polygon"; /** * A rectangle polygon which extend PolygonShape. */ function BoxShape(hx, hy, center, angle) { if (!(this instanceof BoxShape)) { return new BoxShape(hx, hy, center, angle); } BoxShape._super.call(this); this._setAsBox(hx, hy, center, angle); } },{"../util/common":50,"../util/create":51,"./PolygonShape":47}],39:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = ChainShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); var EdgeShape = require("./EdgeShape"); ChainShape._super = Shape; ChainShape.prototype = create(ChainShape._super.prototype); ChainShape.TYPE = "chain"; /** * A chain shape is a free form sequence of line segments. The chain has * two-sided collision, so you can use inside and outside collision. Therefore, * you may use any winding order. Connectivity information is used to create * smooth collisions. * * WARNING: The chain will not collide properly if there are self-intersections. */ 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.clear = function() { // this.m_vertices.length = 0; // this.m_count = 0; // } /** * Create a loop. This automatically adjusts connectivity. * * @param vertices an array of vertices, these are copied * @param count the vertex count */ 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]; // If the code crashes here, it means your vertices are too close together. _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; }; /** * Create a chain with isolated end vertices. * * @param vertices an array of vertices, these are copied * @param count the vertex count */ 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) { // If the code crashes here, it means your vertices are too close together. 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; }; /** * Establish connectivity to a vertex that precedes the first vertex. Don't call * this for loops. */ ChainShape.prototype._setPrevVertex = function(prevVertex) { this.m_prevVertex = prevVertex; this.m_hasPrevVertex = true; }; /** * Establish connectivity to a vertex that follows the last vertex. Don't call * this for loops. */ ChainShape.prototype._setNextVertex = function(nextVertex) { this.m_nextVertex = nextVertex; this.m_hasNextVertex = true; }; /** * @deprecated */ 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() { // edge count = vertex count - 1 return this.m_count - 1; }; // Get a child edge. 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]; } }; /** * This always return false. */ ChainShape.prototype.testPoint = function(xf, p) { return false; }; ChainShape.prototype.rayCast = function(output, input, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1)); return edgeShape.rayCast(output, input, xf, 0); }; ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) { _ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var v1 = Transform.mulVec2(xf, this.getVertex(childIndex)); var v2 = Transform.mulVec2(xf, this.getVertex(childIndex + 1)); aabb.combinePoints(v1, v2); }; /** * Chains have zero mass. */ 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":50,"../util/create":51,"../util/options":52,"./EdgeShape":46}],40:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = CircleShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); CircleShape._super = Shape; CircleShape.prototype = create(CircleShape._super.prototype); CircleShape.TYPE = "circle"; function CircleShape(a, b) { if (!(this instanceof CircleShape)) { return new CircleShape(a, b); } CircleShape._super.call(this); this.m_type = CircleShape.TYPE; this.m_p = Vec2.zero(); this.m_radius = 1; if (typeof a === "object" && Vec2.isValid(a)) { this.m_p.set(a); if (typeof b === "number") { this.m_radius = b; } } else if (typeof a === "number") { this.m_radius = a; } } CircleShape.prototype.getRadius = function() { return this.m_radius; }; CircleShape.prototype.getCenter = function() { return this.m_p; }; CircleShape.prototype.getVertex = function(index) { _ASSERT && common.assert(index == 0); return this.m_p; }; CircleShape.prototype.getVertexCount = function(index) { return 1; }; /** * @deprecated */ CircleShape.prototype._clone = function() { var clone = new CircleShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_p = this.m_p.clone(); return clone; }; CircleShape.prototype.getChildCount = function() { return 1; }; CircleShape.prototype.testPoint = function(xf, p) { var center = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); var d = Vec2.sub(p, center); return Vec2.dot(d, d) <= this.m_radius * this.m_radius; }; // Collision Detection in Interactive 3D Environments by Gino van den Bergen // From Section 3.1.2 // x = s + a * r // norm(x) = radius CircleShape.prototype.rayCast = function(output, input, xf, childIndex) { var position = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); var s = Vec2.sub(input.p1, position); var b = Vec2.dot(s, s) - this.m_radius * this.m_radius; // Solve quadratic equation. 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; // Check for negative discriminant and short segment. if (sigma < 0 || rr < Math.EPSILON) { return false; } // Find the point of intersection of the line with the circle. var a = -(c + Math.sqrt(sigma)); // Is the intersection point on the segment? if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; output.normal = Vec2.add(s, Vec2.mul(a, r)); output.normal.normalize(); return true; } return false; }; CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) { var p = Vec2.add(xf.p, Rot.mulVec2(xf.q, this.m_p)); aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius); }; CircleShape.prototype.computeMass = function(massData, density) { massData.mass = density * Math.PI * this.m_radius * this.m_radius; massData.center = this.m_p; // inertia about the local origin 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":50,"../util/create":51,"../util/options":52}],41:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var CircleShape = require("./CircleShape"); Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact); function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { _ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE); _ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = Transform.mulVec2(xfA, circleA.m_p); var pB = Transform.mulVec2(xfB, circleB.m_p); var distSqr = Vec2.distanceSquared(pB, pA); var rA = circleA.m_radius; var rB = circleB.m_radius; var radius = rA + rB; if (distSqr > radius * radius) { return; } manifold.type = Manifold.e_circles; manifold.localPoint.set(circleA.m_p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); // manifold.points[0].id.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; } exports.CollideCircles = CollideCircles; },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":50,"../util/create":51,"./CircleShape":40}],42:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var 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; // Compute circle position in the frame of the polygon. var c = Transform.mulVec2(xfB, circleB.m_p); var cLocal = Transform.mulTVec2(xfA, c); // Find the min separating edge. 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) { // Early out. return; } if (s > separation) { separation = s; normalIndex = i; } } // Vertices that subtend the incident face. var vertIndex1 = normalIndex; var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; // If the center is inside the polygon ... if (separation < Math.EPSILON) { manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[normalIndex]); manifold.localPoint.setCombine(.5, v1, .5, v2); manifold.points[0].localPoint = 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; } // Compute barycentric coordinates var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1)); var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2)); if (u1 <= 0) { if (Vec2.distanceSquared(cLocal, v1) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint = v1; 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; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.setCombine(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); // manifold.points[0].id.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; } 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; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":50,"./CircleShape":40,"./PolygonShape":47}],43:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var 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); } // Compute contact points for edge versus circle. // This accounts for edge connectivity. function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; // Compute circle in frame of edge var Q = Transform.mulTVec2(xfA, Transform.mulVec2(xfB, circleB.m_p)); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = Vec2.sub(B, A); // Barycentric coordinates 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; // Region A 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; } // Is there an edge connected to A? 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)); // Is the circle in Region AB of the previous edge? 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; } // Region B 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; } // Is there an edge connected to B? 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)); // Is the circle in Region AB of the next edge? 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; } // Region AB var den = Vec2.dot(e, e); _ASSERT && common.assert(den > 0); var P = Vec2.combine(u / den, A, v / den, B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } var n = Vec2.neo(-e.y, e.x); if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) { n.set(-n.x, -n.y); } n.normalize(); manifold.type = Manifold.e_faceA; manifold.localNormal = 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":50,"../util/create":51,"./ChainShape":39,"./CircleShape":40,"./EdgeShape":46}],44:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var 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); } // EPAxis Type var e_unknown = -1; var e_edgeA = 1; var e_edgeB = 2; // VertexType unused? var e_isolated = 0; var e_concave = 1; var e_convex = 2; // This structure is used to keep track of the best separating axis. function EPAxis() { this.type; // Type this.index; this.separation; } // This holds polygon B expressed in frame A. function TempPolygon() { this.vertices = []; // Vec2[Settings.maxPolygonVertices] this.normals = []; // Vec2[Settings.maxPolygonVertices]; this.count = 0; } // Reference face used for clipping function ReferenceFace() { this.i1, this.i2; // int this.v1, this.v2; // v this.normal = Vec2.zero(); this.sideNormal1 = Vec2.zero(); this.sideOffset1; // float this.sideNormal2 = Vec2.zero(); this.sideOffset2; } // reused var edgeAxis = new EPAxis(); var polygonAxis = new EPAxis(); var polygonBA = new TempPolygon(); var rf = new ReferenceFace(); /** * This function collides and edge and a polygon, taking into account edge * adjacency. */ function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) { // Algorithm: // 1. Classify v1 and v2 // 2. Classify polygon centroid as front or back // 3. Flip normal if necessary // 4. Initialize normal range to [-pi, pi] about face normal // 5. Adjust normal range according to adjacent edges // 6. Visit each separating axes, only accept axes within the range // 7. Return if _any_ axis indicates separation // 8. Clip var m_type1, m_type2; // VertexType unused? var xf = Transform.mulTXf(xfA, xfB); var centroidB = Transform.mulVec2(xf, polygonB.m_centroid); var v0 = edgeA.m_vertex0; var v1 = edgeA.m_vertex1; var v2 = edgeA.m_vertex2; var v3 = edgeA.m_vertex3; var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = Vec2.sub(v2, v1); edge1.normalize(); var normal1 = Vec2.neo(edge1.y, -edge1.x); var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; // Is there a preceding edge? 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); } // Is there a following edge? 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(); // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } } else if (convex1) { front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal1); } } else if (convex2) { front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.setMul(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.setMul(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal2); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.set(normal1); } else { normal.setMul(-1, normal1); lowerLimit.setMul(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.setMul(-1, normal1); upperLimit.setMul(-1, normal1); } else { normal.setMul(-1, normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } } // Get polygonB in frameA polygonBA.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { polygonBA.vertices[i] = Transform.mulVec2(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mulVec2(xf.q, polygonB.m_normals[i]); } var radius = 2 * Settings.polygonRadius; manifold.pointCount = 0; { // ComputeEdgeSeparation 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 no valid normal can be found than this edge should not collide. if (edgeAxis.type == e_unknown) { return; } if (edgeAxis.separation > radius) { return; } { // ComputePolygonSeparation 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) { // No collision polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; break; } // Adjacency 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; } // Use hysteresis for jitter reduction. 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; // Search for the polygon normal that is most anti-parallel to the edge // normal. var bestIndex = 0; var bestValue = Vec2.dot(normal, polygonBA.normals[0]); for (var i = 1; i < polygonBA.count; ++i) { var value = Vec2.dot(normal, polygonBA.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0; ie[0].v = polygonBA.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = Manifold.e_face; ie[0].id.cf.typeB = Manifold.e_vertex; ie[1].v = polygonBA.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = Manifold.e_face; ie[1].id.cf.typeB = Manifold.e_vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.normal.set(normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.normal.setMul(-1, normal1); } } else { manifold.type = Manifold.e_faceB; ie[0].v = v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = Manifold.e_vertex; ie[0].id.cf.typeB = Manifold.e_face; ie[1].v = v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = Manifold.e_vertex; ie[1].id.cf.typeB = Manifold.e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0; rf.v1 = polygonBA.vertices[rf.i1]; rf.v2 = polygonBA.vertices[rf.i2]; rf.normal.set(polygonBA.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.setMul(-1, rf.sideNormal1); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; // Clip to box side 1 np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < Settings.maxManifoldPoints) { return; } // Clip to negative box side 1 np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < Settings.maxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. 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]; // ManifoldPoint 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":50,"../util/create":51,"./ChainShape":39,"./EdgeShape":46,"./PolygonShape":47}],45:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var 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); } /** * Find the max separation between poly1 and poly2 using edge normals from * poly1. */ function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulTXf(xf2, xf1); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { // Get poly1 normal in frame2. var n = Rot.mulVec2(xf.q, n1s[i]); var v1 = Transform.mulVec2(xf, v1s[i]); // Find deepest point for normal 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; } } // used to keep last FindMaxSeparation call values FindMaxSeparation._maxSeparation = maxSeparation; FindMaxSeparation._bestIndex = bestIndex; } /** * @param {ClipVertex[2]} c * @param {int} edge1 */ 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); // Get the normal of the reference edge in poly2's frame. var normal1 = Rot.mulT(xf2.q, Rot.mulVec2(xf1.q, normals1[edge1])); // Find the incident edge on poly2. 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; } } // Build the clip vertices for the incident edge. var i1 = index; var i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = Transform.mulVec2(xf2, vertices2[i1]); c[0].id.cf.indexA = edge1; c[0].id.cf.indexB = i1; c[0].id.cf.typeA = Manifold.e_face; c[0].id.cf.typeB = Manifold.e_vertex; c[1].v = Transform.mulVec2(xf2, vertices2[i2]); c[1].id.cf.indexA = edge1; c[1].id.cf.indexB = i2; c[1].id.cf.typeA = Manifold.e_face; c[1].id.cf.typeB = Manifold.e_vertex; } /** * * Find edge normal of max separation on A - return if separating axis is found<br> * Find edge normal of max separation on B - return if separation axis is found<br> * Choose reference edge as min(minA, minB)<br> * Find incident edge<br> * Clip * * The normal points from 1 to 2 */ 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; // reference polygon var poly2; // incident polygon var xf1; var xf2; var edge1; // reference edge 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.combine(.5, v11, .5, v12); var tangent = Rot.mulVec2(xf1.q, localTangent); var normal = Vec2.cross(tangent, 1); v11 = Transform.mulVec2(xf1, v11); v12 = Transform.mulVec2(xf1, v12); // Face offset. var frontOffset = Vec2.dot(normal, v11); // Side offsets, extended by polytope skin thickness. var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; // Clip incident edge against extruded edge1 side edges. var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; // Clip to box side 1 np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg(tangent), sideOffset1, iv1); if (np < 2) { return; } // Clip to negative box side 1 np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } // Now clipPoints2 contains the clipped points. 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]; // ManifoldPoint cp.localPoint.set(Transform.mulTVec2(xf2, clipPoints2[i].v)); cp.id = clipPoints2[i].id; if (flip) { // Swap features var cf = cp.id.cf; // ContactFeature 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":50,"./PolygonShape":47}],46:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = EdgeShape; var create = require("../util/create"); var options = require("../util/options"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); EdgeShape._super = Shape; EdgeShape.prototype = create(EdgeShape._super.prototype); EdgeShape.TYPE = "edge"; /** * A line segment (edge) shape. These can be connected in chains or loops to * other edge shapes. The connectivity information is used to ensure correct * contact normals. */ 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; // These are the edge vertices this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero(); this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero(); // Optional adjacent vertices. These are used for smooth collision. // Used by chain shape. 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; }; /** * Set this as an isolated edge. */ 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; }; /** * @deprecated */ 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; }; // p = p1 + t * d // v = v1 + s * e // p1 + t * d = v1 + s * e // s * e - t * d = p1 - v1 EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) { // NOT_USED(childIndex); // Put the ray into the edge's frame of reference. var p1 = Rot.mulTVec2(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulTVec2(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = Vec2.sub(v2, v1); var normal = Vec2.neo(e.y, -e.x); normal.normalize(); // q = p1 + t * d // dot(normal, q - v1) = 0 // dot(normal, p1 - v1) + t * dot(normal, d) = 0 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)); // q = v1 + s * r // s = dot(q - v1, r) / dot(r, r) var r = Vec2.sub(v2, v1); var rr = Vec2.dot(r, r); if (rr == 0) { return false; } var s = Vec2.dot(Vec2.sub(q, v1), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; if (numerator > 0) { output.normal = Rot.mulVec2(xf.q, normal).neg(); } else { output.normal = Rot.mulVec2(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mulVec2(xf, this.m_vertex1); var v2 = Transform.mulVec2(xf, this.m_vertex2); aabb.combinePoints(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.setCombine(.5, this.m_vertex1, .5, this.m_vertex2); massData.I = 0; }; EdgeShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_vertex1); proxy.m_vertices.push(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":51,"../util/options":52}],47:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PolygonShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); PolygonShape._super = Shape; PolygonShape.prototype = create(PolygonShape._super.prototype); PolygonShape.TYPE = "polygon"; /** * A convex polygon. It is assumed that the interior of the polygon is to the * left of each edge. Polygons have a maximum number of vertices equal to * Settings.maxPolygonVertices. In most cases you should not need many vertices * for a convex polygon. extends Shape */ 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 = []; // Vec2[Settings.maxPolygonVertices] this.m_normals = []; // Vec2[Settings.maxPolygonVertices] 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]; }; /** * @deprecated */ 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; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). var pRef = Vec2.zero(); if (false) { // This code would put the reference point inside the polygon. 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) { // Triangle vertices. 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; // Area weighted centroid c.addMul(triangleArea * inv3, p1); c.addMul(triangleArea * inv3, p2); c.addMul(triangleArea * inv3, p3); } // Centroid _ASSERT && common.assert(area > Math.EPSILON); c.mul(1 / area); return c; } /** * @private * * Create a convex hull from the given array of local points. The count must be * in the range [3, Settings.maxPolygonVertices]. * * Warning: the points may be re-ordered, even if they form a convex polygon * Warning: collinear points are handled but not removed. Collinear points may * lead to poor stacking behavior. */ PolygonShape.prototype._set = function(vertices) { _ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices); if (vertices.length < 3) { this._setAsBox(1, 1); return; } var n = Math.min(vertices.length, Settings.maxPolygonVertices); // Perform welding and copy vertices into local buffer. var ps = []; // [Settings.maxPolygonVertices]; 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) { // Polygon is degenerate. _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } // Create the convex hull using the Gift wrapping algorithm // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm // Find the right most point on the hull 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 = []; // [Settings.maxPolygonVertices]; 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; } // Collinearity check if (c == 0 && v.lengthSquared() > r.lengthSquared()) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } if (m < 3) { // Polygon is degenerate. _ASSERT && common.assert(false); this._setAsBox(1, 1); return; } this.m_count = m; // Copy vertices. for (var i = 0; i < m; ++i) { this.m_vertices[i] = ps[hull[i]]; } // Compute normals. Ensure the edges have non-zero length. 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(); } // Compute the polygon centroid. this.m_centroid = ComputeCentroid(this.m_vertices, m); }; /** * @private */ PolygonShape.prototype._setAsBox = function(hx, hy, center, angle) { this.m_vertices[0] = Vec2.neo(-hx, -hy); this.m_vertices[1] = Vec2.neo(hx, -hy); this.m_vertices[2] = Vec2.neo(hx, hy); this.m_vertices[3] = Vec2.neo(-hx, hy); this.m_normals[0] = Vec2.neo(0, -1); this.m_normals[1] = Vec2.neo(1, 0); this.m_normals[2] = Vec2.neo(0, 1); this.m_normals[3] = Vec2.neo(-1, 0); this.m_count = 4; if (Vec2.isValid(center)) { angle = angle || 0; this.m_centroid.set(center); var xf = Transform.identity(); xf.p.set(center); xf.q.set(angle); // Transform vertices and normals. for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i] = Transform.mulVec2(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mulVec2(xf.q, this.m_normals[i]); } } }; PolygonShape.prototype.testPoint = function(xf, p) { var pLocal = Rot.mulTVec2(xf.q, Vec2.sub(p, xf.p)); for (var i = 0; i < this.m_count; ++i) { var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i])); if (dot > 0) { return false; } } return true; }; PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) { // Put the ray into the polygon's frame of reference. var p1 = Rot.mulTVec2(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulTVec2(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var lower = 0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 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 { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if (denominator < 0 && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } // The use of epsilon here causes the assert on lower to trip // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. // if (upper < lower - Math.EPSILON) if (upper < lower) { return false; } } _ASSERT && common.assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; output.normal = Rot.mulVec2(xf.q, this.m_normals[index]); return true; } return false; }; PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) { var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < this.m_count; ++i) { var v = Transform.mulVec2(xf, this.m_vertices[i]); minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } aabb.lowerBound.set(minX, minY); aabb.upperBound.set(maxX, maxY); aabb.extend(this.m_radius); }; PolygonShape.prototype.computeMass = function(massData, density) { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.x = (1/mass) * rho * int(x * dA) // centroid.y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. _ASSERT && common.assert(this.m_count >= 3); var center = Vec2.zero(); var area = 0; var I = 0; // s is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). var s = Vec2.zero(); // This code would put the reference point inside the polygon. 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) { // Triangle vertices. 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; // Area weighted centroid center.addCombine(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } // Total mass massData.mass = density * area; // Center of mass _ASSERT && common.assert(area > Math.EPSILON); center.mul(1 / area); massData.center.setCombine(1, center, 1, s); // Inertia tensor relative to the local origin (point s). massData.I = density * I; // Shift to center of mass then to original body origin. massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center)); }; // Validate convexity. This is a very time consuming operation. // @returns true if valid 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":50,"../util/create":51,"../util/options":52}],48:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _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; }; } },{}],49:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports.now = function() { return Date.now(); }; module.exports.diff = function(time) { return Date.now() - time; }; },{}],50:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.debug = function() { if (!_DEBUG) return; console.log.apply(console, arguments); }; exports.assert = function(statement, err, log) { if (!_ASSERT) return; if (statement) return; log && console.log(log); throw new Error(err); }; },{}],51:[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() {} } },{}],52:[function(require,module,exports){ var _DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; var _ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function(to, from) { if (to === null || typeof to === "undefined") { to = {}; } for (var key in from) { if (from.hasOwnProperty(key) && typeof to[key] === "undefined") { to[key] = from[key]; } } if (typeof Object.getOwnPropertySymbols === "function") { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") { to[symbol] = from[symbol]; } } } return to; }; },{}]},{},[1])(1) });
version https://git-lfs.github.com/spec/v1 oid sha256:3362b51608fe53e6e9b0e697537ca16605ffe0f21b06c2d7937a1d6d3ca24ec0 size 96320