diff --git a/angular-environment/angular-environment-tests.ts b/angular-environment/angular-environment-tests.ts index b3f83b14f..e7c077faf 100644 --- a/angular-environment/angular-environment-tests.ts +++ b/angular-environment/angular-environment-tests.ts @@ -1,30 +1,30 @@ -/// -var envServiceProvider: angular.environment.ServiceProvider; -var envService: angular.environment.Service; - -envServiceProvider.config({ - domains: { - development: ['localhost', 'dev.local'], - production: ['acme.com', 'acme.net', 'acme.org'] - }, - vars: { - development: { - apiUrl: '//localhost/api', - staticUrl: '//localhost/static' - }, - production: { - apiUrl: '//api.acme.com/v2', - staticUrl: '//static.acme.com' - } - } -}); - -envServiceProvider.check(); - -envService.get(); - -envService.set('production'); - -var isProd: boolean = envService.is('production'); - -var val: any = envService.read('apiUrl'); +/// +var envServiceProvider: angular.environment.ServiceProvider; +var envService: angular.environment.Service; + +envServiceProvider.config({ + domains: { + development: ['localhost', 'dev.local'], + production: ['acme.com', 'acme.net', 'acme.org'] + }, + vars: { + development: { + apiUrl: '//localhost/api', + staticUrl: '//localhost/static' + }, + production: { + apiUrl: '//api.acme.com/v2', + staticUrl: '//static.acme.com' + } + } +}); + +envServiceProvider.check(); + +envService.get(); + +envService.set('production'); + +var isProd: boolean = envService.is('production'); + +var val: any = envService.read('apiUrl'); diff --git a/angular-environment/angular-environment.d.ts b/angular-environment/angular-environment.d.ts index 6651817b6..bb38b8f0a 100644 --- a/angular-environment/angular-environment.d.ts +++ b/angular-environment/angular-environment.d.ts @@ -1,52 +1,52 @@ -// Type definitions for angular-environment v1.0.4 -// Project: https://github.com/juanpablob/angular-environment -// Definitions by: Matt Wheatley -// Definitions: https://github.com/LiberisLabs - -declare module angular.environment { - interface ServiceProvider { - /** - * Sets the configuration object - */ - config: (config: angular.environment.Config) => void; - /** - * Evaluates the current domain and - * loads the correct environment variables. - */ - check: () => void; - } - interface Service { - /** - * Retrieve the current environment - */ - get: () => string, - - /** - * Force sets the current environment - */ - set: (environment: string) => void, - - /** - * Evaluates current environment against - * environment parameter. - */ - is: (environment: string) => boolean, - - /** - * Retrieves the correct version of a - * variable for the current environment. - */ - read: (key: string) => any; - } - - interface Config { - /** - * Map of domains to their environments - */ - domains: { [environment: string]: Array }, - /** - * List of variables split by environment - */ - vars: { [environment: string]: { [variable: string]: any }}, - } -} +// Type definitions for angular-environment v1.0.4 +// Project: https://github.com/juanpablob/angular-environment +// Definitions by: Matt Wheatley +// Definitions: https://github.com/LiberisLabs + +declare module angular.environment { + interface ServiceProvider { + /** + * Sets the configuration object + */ + config: (config: angular.environment.Config) => void; + /** + * Evaluates the current domain and + * loads the correct environment variables. + */ + check: () => void; + } + interface Service { + /** + * Retrieve the current environment + */ + get: () => string, + + /** + * Force sets the current environment + */ + set: (environment: string) => void, + + /** + * Evaluates current environment against + * environment parameter. + */ + is: (environment: string) => boolean, + + /** + * Retrieves the correct version of a + * variable for the current environment. + */ + read: (key: string) => any; + } + + interface Config { + /** + * Map of domains to their environments + */ + domains: { [environment: string]: Array }, + /** + * List of variables split by environment + */ + vars: { [environment: string]: { [variable: string]: any }}, + } +} diff --git a/express/express-tests.ts b/express/express-tests.ts index 6ac53bf2d..d344dc6eb 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,70 +1,70 @@ -/// - -import * as express from 'express'; -var app = express(); - -app.engine('jade', require('jade').__express); -app.engine('html', require('ejs').renderFile); - -express.static.mime.define({ - 'application/fx': ['fx'] -}); -app.use('/static', express.static(__dirname + '/public')); - -// simple logger -app.use(function(req, res, next){ - console.log('%s %s', req.method, req.url); - next(); -}); - -app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { - console.error(err); - next(err); -}); - - -app.get('/', function(req, res){ - res.send('hello world'); -}); - -const router = express.Router(); - - -const pathStr : string = 'test'; -const pathRE : RegExp = /test/; -const path = true? pathStr : pathRE; - -router.get(path); -router.put(path) -router.post(path); -router.delete(path); -router.get(pathStr); -router.put(pathStr) -router.post(pathStr); -router.delete(pathStr); -router.get(pathRE); -router.put(pathRE) -router.post(pathRE); -router.delete(pathRE); - -router.use((req, res, next) => { next(); }) -router.route('/users') - .get((req, res, next) => { - res.send(req.query['token']); - }); - -router.get('/user/:id', function(req, res, next) { - if (req.params.id == 0) next('route'); - else next(); -}, function(req, res, next) { - res.render('regular'); -}); - -app.use((req, res, next) => { - // hacky trick, router is just a handler - router(req, res, next); -}); - -app.use(router); - -app.listen(3000); +/// + +import * as express from 'express'; +var app = express(); + +app.engine('jade', require('jade').__express); +app.engine('html', require('ejs').renderFile); + +express.static.mime.define({ + 'application/fx': ['fx'] +}); +app.use('/static', express.static(__dirname + '/public')); + +// simple logger +app.use(function(req, res, next){ + console.log('%s %s', req.method, req.url); + next(); +}); + +app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + console.error(err); + next(err); +}); + + +app.get('/', function(req, res){ + res.send('hello world'); +}); + +const router = express.Router(); + + +const pathStr : string = 'test'; +const pathRE : RegExp = /test/; +const path = true? pathStr : pathRE; + +router.get(path); +router.put(path) +router.post(path); +router.delete(path); +router.get(pathStr); +router.put(pathStr) +router.post(pathStr); +router.delete(pathStr); +router.get(pathRE); +router.put(pathRE) +router.post(pathRE); +router.delete(pathRE); + +router.use((req, res, next) => { next(); }) +router.route('/users') + .get((req, res, next) => { + res.send(req.query['token']); + }); + +router.get('/user/:id', function(req, res, next) { + if (req.params.id == 0) next('route'); + else next(); +}, function(req, res, next) { + res.render('regular'); +}); + +app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); +}); + +app.use(router); + +app.listen(3000); diff --git a/express/express.d.ts b/express/express.d.ts index 171b6e6a7..3404ce903 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -1,1081 +1,1081 @@ -// Type definitions for Express 4.x -// Project: http://expressjs.com -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/* =================== USAGE =================== - - import * as express from "express"; - var app = express(); - - =============================================== */ - -/// -/// - -declare module Express { - - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } -} - - -declare module "express" { - import * as http from "http"; - import * as serveStatic from "serve-static"; - - function e(): e.Express; - - module e { - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - head(...handler: RequestHandler[]): IRoute; - } - - interface IRouterMatcher { - (name: string|RegExp, ...handlers: RequestHandler[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; - - route(path: string): IRoute; - - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler|RequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler|RequestHandler): T; - use(path: string[], ...handler: RequestHandler[]): T; - use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandler[]): T; - use(path: RegExp, handler: ErrorRequestHandler): T; - use(path:string, router:Router): T; - } - - export function Router(options?: any): Router; - - export interface Router extends IRouter {} - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.ServerRequest, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get (name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(type: string): string; - - accepts(type: string[]): string; - - /** - * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. - * If none of the specified charsets is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param charset - */ - acceptsCharsets(charset?: string|string[]): string[]; - - /** - * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. - * If none of the specified encodings is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param encoding - */ - acceptsEncodings(encoding?: string|string[]): string[]; - - /** - * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. - * If none of the specified languages is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * - * @param lang - */ - acceptsLanguages(lang?: string|string[]): string[]; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - hostname: string; - - /** - * @deprecated Use hostname instead. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - user: any; - - authenticatedUser: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - - baseUrl: string; - - app: Application; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, fn: Errback): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get (field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; - render(view: string, callback?: (err: Error, html: string) => void ): void; - - locals: any; - - charset: string; - } - - interface NextFunction { - (): void; - (err: any): void; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } - - interface Handler extends RequestHandler {} - - interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, param: any): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string|RegExp, ...handlers: RequestHandler[]): Application; - }; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - route(path: string): IRoute; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. - */ - createApplication(): Application; - - createServer(): Application; - - application: any; - - request: Request; - - response: Response; - } - - var static: typeof serveStatic; - } - - export = e; -} +// Type definitions for Express 4.x +// Project: http://expressjs.com +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import * as express from "express"; + var app = express(); + + =============================================== */ + +/// +/// + +declare module Express { + + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/borisyankov/DefinitelyTyped/blob/master/method-override/method-override.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } +} + + +declare module "express" { + import * as http from "http"; + import * as serveStatic from "serve-static"; + + function e(): e.Express; + + module e { + interface IRoute { + path: string; + stack: any; + all(...handler: RequestHandler[]): IRoute; + get(...handler: RequestHandler[]): IRoute; + post(...handler: RequestHandler[]): IRoute; + put(...handler: RequestHandler[]): IRoute; + delete(...handler: RequestHandler[]): IRoute; + patch(...handler: RequestHandler[]): IRoute; + options(...handler: RequestHandler[]): IRoute; + head(...handler: RequestHandler[]): IRoute; + } + + interface IRouterMatcher { + (name: string|RegExp, ...handlers: RequestHandler[]): T; + } + + interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn + */ + param(name: string, handler: RequestParamHandler): T; + param(name: string, matcher: RegExp): T; + param(name: string, mapper: (param: any) => any): T; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; + + route(path: string): IRoute; + + use(...handler: RequestHandler[]): T; + use(handler: ErrorRequestHandler|RequestHandler): T; + use(path: string, ...handler: RequestHandler[]): T; + use(path: string, handler: ErrorRequestHandler|RequestHandler): T; + use(path: string[], ...handler: RequestHandler[]): T; + use(path: string[], handler: ErrorRequestHandler): T; + use(path: RegExp, ...handler: RequestHandler[]): T; + use(path: RegExp, handler: ErrorRequestHandler): T; + use(path:string, router:Router): T; + } + + export function Router(options?: any): Router; + + export interface Router extends IRouter {} + + interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean; + } + + interface Errback { (err: Error): void; } + + interface Request extends http.ServerRequest, Express.Request { + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get (name: string): string; + + header(name: string): string; + + headers: { [key: string]: string; }; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(type: string): string; + + accepts(type: string[]): string; + + /** + * Returns the first accepted charset of the specified character sets, + * based on the request’s Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param charset + */ + acceptsCharsets(charset?: string|string[]): string[]; + + /** + * Returns the first accepted encoding of the specified encodings, + * based on the request’s Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param encoding + */ + acceptsEncodings(encoding?: string|string[]): string[]; + + /** + * Returns the first accepted language of the specified languages, + * based on the request’s Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * + * @param lang + */ + acceptsLanguages(lang?: string|string[]): string[]; + + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): any[]; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): boolean; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + hostname: string; + + /** + * @deprecated Use hostname instead. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + //body: { username: string; password: string; remember: boolean; title: string; }; + body: any; + + //cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: any; + + user: any; + + authenticatedUser: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + + baseUrl: string; + + app: Application; + } + + interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; + } + + interface Send { + (status: number, body?: any): Response; + (body: any): Response; + } + + interface Response extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): Response; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Response; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): Response; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ + sendFile(path: string): void; + sendFile(path: string, options: any): void; + sendFile(path: string, fn: Errback): void; + sendFile(path: string, options: any, fn: Errback): void; + + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, fn: Errback): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ + download(path: string): void; + download(path: string, filename: string): void; + download(path: string, fn: Errback): void; + download(path: string, filename: string, fn: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + contentType(type: string): Response; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + type(type: string): Response; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): Response; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): Response; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): Response; + set(field: string, value?: string): Response; + + header(field: any): Response; + header(field: string, value?: string): Response; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** + * Get value for header `field`. + * + * @param field + */ + get (field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): Response; + cookie(name: string, val: any, options: CookieOptions): Response; + cookie(name: string, val: any): Response; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string): Response; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: Object, callback?: (err: Error, html: string) => void ): void; + render(view: string, callback?: (err: Error, html: string) => void ): void; + + locals: any; + + charset: string; + } + + interface NextFunction { + (): void; + (err: any): void; + } + + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; + } + + interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; + } + + interface Handler extends RequestHandler {} + + interface RequestParamHandler { + (req: Request, res: Response, next: NextFunction, param: any): any; + } + + interface Application extends IRouter, Express.Application { + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set(setting: string, val: any): Application; + get: { + (name: string): any; // Getter + (name: string|RegExp, ...handlers: RequestHandler[]): Application; + }; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): boolean; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): Application; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): Application; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(fn: Function): Application; + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; + listen(port: number, hostname: string, callback?: Function): http.Server; + listen(port: number, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + + route(path: string): IRoute; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + } + + interface Express extends Application { + /** + * Framework version. + */ + version: string; + + /** + * Expose mime. + */ + mime: string; + + (): Application; + + /** + * Create an express application. + */ + createApplication(): Application; + + createServer(): Application; + + application: any; + + request: Request; + + response: Response; + } + + var static: typeof serveStatic; + } + + export = e; +} diff --git a/iscroll/iscroll-5.d.ts b/iscroll/iscroll-5.d.ts index 8b7a80543..686fa6821 100644 --- a/iscroll/iscroll-5.d.ts +++ b/iscroll/iscroll-5.d.ts @@ -1,91 +1,91 @@ -// Type definitions for iScroll 5 -// Project: http://cubiq.org/iscroll-5-ready-for-beta-test -// Definitions by: Christiaan Rakowski -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface IScrollOptions { - //hScroll?: boolean; - //vScroll?: boolean; - x?: number; - y?: number; - bounce?: boolean; - bounceLock?: boolean; - momentum?: boolean; - lockDirection?: boolean; - useTransform?: boolean; - useTransition?: boolean; - topOffset?: number; - checkDOMChanges?: boolean; - handleClick?: boolean; - - // Scrollbar - hScrollbar?: boolean; - vScrollbar?: boolean; - fixedScrollbar?: boolean; - hideScrollbar?: boolean; - fadeScrollbar?: boolean; - scrollbarClass?: string; - - // Zoom - zoom?: boolean; - zoomMin?: number; - zoomMax?: number; - doubleTapZoom?: number; - wheelAction?: string; - - - ///String or boolean - snap?: any; - snapThreshold?: number; - - //new in IScroll 5? - - resizeIndicator?: boolean; - mouseWheelSpeed?: number; - startX?: number; - startY?: number; - scrollX?: boolean; - scrollY?: boolean; - directionLockThreshold?: number; - - bounceTime?: number; - - ///String or function - bounceEasing?: any; - - preventDefault?: boolean; - preventDefaultException?: boolean; - - HWCompositing?: boolean; - - freeScroll?: boolean; - - resizePolling?: number; - tap?: boolean; - click?: boolean; - invertWheelDirection?: boolean; - - ///Boolean or string - eventPassthrough?: any; -} - -declare class IScroll { - - constructor (element: string, options?: IScrollOptions); - constructor (element: HTMLElement, options?: IScrollOptions); - - destroy(): void; - refresh(): void; - scrollTo(x: number, y: number, time?: number, relative?: boolean): void; - scrollToElement(element: string, time?: number): void; - scrollToElement(element: HTMLElement, time?: number): void; - goToPage(pageX: number, pageY: number, time?: number): void; - disable(): void; - enable(): void; - stop(): void; - zoom(x: number, y: number, scale: number, time?: number): void; - isReady(): boolean; - - // Events - on: (type: string, fn: () => void) => void; -} +// Type definitions for iScroll 5 +// Project: http://cubiq.org/iscroll-5-ready-for-beta-test +// Definitions by: Christiaan Rakowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IScrollOptions { + //hScroll?: boolean; + //vScroll?: boolean; + x?: number; + y?: number; + bounce?: boolean; + bounceLock?: boolean; + momentum?: boolean; + lockDirection?: boolean; + useTransform?: boolean; + useTransition?: boolean; + topOffset?: number; + checkDOMChanges?: boolean; + handleClick?: boolean; + + // Scrollbar + hScrollbar?: boolean; + vScrollbar?: boolean; + fixedScrollbar?: boolean; + hideScrollbar?: boolean; + fadeScrollbar?: boolean; + scrollbarClass?: string; + + // Zoom + zoom?: boolean; + zoomMin?: number; + zoomMax?: number; + doubleTapZoom?: number; + wheelAction?: string; + + + ///String or boolean + snap?: any; + snapThreshold?: number; + + //new in IScroll 5? + + resizeIndicator?: boolean; + mouseWheelSpeed?: number; + startX?: number; + startY?: number; + scrollX?: boolean; + scrollY?: boolean; + directionLockThreshold?: number; + + bounceTime?: number; + + ///String or function + bounceEasing?: any; + + preventDefault?: boolean; + preventDefaultException?: boolean; + + HWCompositing?: boolean; + + freeScroll?: boolean; + + resizePolling?: number; + tap?: boolean; + click?: boolean; + invertWheelDirection?: boolean; + + ///Boolean or string + eventPassthrough?: any; +} + +declare class IScroll { + + constructor (element: string, options?: IScrollOptions); + constructor (element: HTMLElement, options?: IScrollOptions); + + destroy(): void; + refresh(): void; + scrollTo(x: number, y: number, time?: number, relative?: boolean): void; + scrollToElement(element: string, time?: number): void; + scrollToElement(element: HTMLElement, time?: number): void; + goToPage(pageX: number, pageY: number, time?: number): void; + disable(): void; + enable(): void; + stop(): void; + zoom(x: number, y: number, scale: number, time?: number): void; + isReady(): boolean; + + // Events + on: (type: string, fn: () => void) => void; +} diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index e94cc262e..50679d86d 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -1,496 +1,496 @@ -// Type definitions for Jasmine 2.2 -// Project: http://jasmine.github.io/ -// Definitions by: Boris Yankov , Theodore Brown , David Pärsson -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -// For ddescribe / iit use : https://github.com/borisyankov/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts - -declare function describe(description: string, specDefinitions: () => void): void; -declare function fdescribe(description: string, specDefinitions: () => void): void; -declare function xdescribe(description: string, specDefinitions: () => void): void; - -declare function it(expectation: string, assertion?: () => void, timeout?: number): void; -declare function it(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; -declare function fit(expectation: string, assertion?: () => void, timeout?: number): void; -declare function fit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: () => void, timeout?: number): void; -declare function xit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; - -/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ -declare function pending(reason?: string): void; - -declare function beforeEach(action: () => void, timeout?: number): void; -declare function beforeEach(action: (done: () => void) => void, timeout?: number): void; -declare function afterEach(action: () => void, timeout?: number): void; -declare function afterEach(action: (done: () => void) => void, timeout?: number): void; - -declare function beforeAll(action: () => void, timeout?: number): void; -declare function beforeAll(action: (done: () => void) => void, timeout?: number): void; -declare function afterAll(action: () => void, timeout?: number): void; -declare function afterAll(action: (done: () => void) => void, timeout?: number): void; - -declare function expect(spy: Function): jasmine.Matchers; -declare function expect(actual: any): jasmine.Matchers; - -declare function fail(e?: any): void; - -declare function spyOn(object: any, method: string): jasmine.Spy; - -declare function runs(asyncMethod: Function): void; -declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; -declare function waits(timeout?: number): void; - -declare module jasmine { - - var clock: () => Clock; - - function any(aclass: any): Any; - function anything(): Any; - function arrayContaining(sample: any[]): ArrayContaining; - function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: Function): Spy; - function createSpyObj(baseName: string, methodNames: any[]): any; - function createSpyObj(baseName: string, methodNames: any[]): T; - function pp(value: any): string; - function getEnv(): Env; - function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - function addMatchers(matchers: CustomMatcherFactories): void; - function stringMatching(str: string): Any; - function stringMatching(str: RegExp): Any; - - interface Any { - - new (expectedClass: any): any; - - jasmineMatches(other: any): boolean; - jasmineToString(): string; - } - - // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() - interface ArrayLike { - length: number; - [n: number]: T; - } - - interface ArrayContaining { - new (sample: any[]): any; - - asymmetricMatch(other: any): boolean; - jasmineToString(): string; - } - - interface ObjectContaining { - new (sample: any): any; - - jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; - jasmineToString(): string; - } - - interface Block { - - new (env: Env, func: SpecFunction, spec: Spec): any; - - execute(onComplete: () => void): void; - } - - interface WaitsBlock extends Block { - new (env: Env, timeout: number, spec: Spec): any; - } - - interface WaitsForBlock extends Block { - new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; - } - - interface Clock { - install(): void; - uninstall(): void; - /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ - tick(ms: number): void; - mockDate(date?: Date): void; - } - - interface CustomEqualityTester { - (first: any, second: any): boolean; - } - - interface CustomMatcher { - compare(actual: T, expected: T): CustomMatcherResult; - compare(actual: any, expected: any): CustomMatcherResult; - } - - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } - - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - interface CustomMatcherResult { - pass: boolean; - message?: string; - } - - interface MatchersUtil { - equals(a: any, b: any, customTesters?: Array): boolean; - contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; - } - - interface Env { - setTimeout: any; - clearTimeout: void; - setInterval: any; - clearInterval: void; - updateInterval: number; - - currentSpec: Spec; - - matchersClass: Matchers; - - version(): any; - versionString(): string; - nextSpecId(): number; - addReporter(reporter: Reporter): void; - execute(): void; - describe(description: string, specDefinitions: () => void): Suite; - // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these - beforeEach(beforeEachFunction: () => void): void; - beforeAll(beforeAllFunction: () => void): void; - currentRunner(): Runner; - afterEach(afterEachFunction: () => void): void; - afterAll(afterAllFunction: () => void): void; - xdescribe(desc: string, specDefinitions: () => void): XSuite; - it(description: string, func: () => void): Spec; - // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these - xit(desc: string, func: () => void): XSpec; - compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; - compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; - equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; - contains_(haystack: any, needle: any): boolean; - addCustomEqualityTester(equalityTester: CustomEqualityTester): void; - addMatchers(matchers: CustomMatcherFactories): void; - specFilter(spec: Spec): boolean; - } - - interface FakeTimer { - - new (): any; - - reset(): void; - tick(millis: number): void; - runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; - scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; - } - - interface HtmlReporter { - new (): any; - } - - interface HtmlSpecFilter { - new (): any; - } - - interface Result { - type: string; - } - - interface NestedResults extends Result { - description: string; - - totalCount: number; - passedCount: number; - failedCount: number; - - skipped: boolean; - - rollupCounts(result: NestedResults): void; - log(values: any): void; - getItems(): Result[]; - addResult(result: Result): void; - passed(): boolean; - } - - interface MessageResult extends Result { - values: any; - trace: Trace; - } - - interface ExpectationResult extends Result { - matcherName: string; - passed(): boolean; - expected: any; - actual: any; - message: string; - trace: Trace; - } - - interface Trace { - name: string; - message: string; - stack: any; - } - - interface PrettyPrinter { - - new (): any; - - format(value: any): void; - iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; - emitScalar(value: any): void; - emitString(value: string): void; - emitArray(array: any[]): void; - emitObject(obj: any): void; - append(value: any): void; - } - - interface StringPrettyPrinter extends PrettyPrinter { - } - - interface Queue { - - new (env: any): any; - - env: Env; - ensured: boolean[]; - blocks: Block[]; - running: boolean; - index: number; - offset: number; - abort: boolean; - - addBefore(block: Block, ensure?: boolean): void; - add(block: any, ensure?: boolean): void; - insertNext(block: any, ensure?: boolean): void; - start(onComplete?: () => void): void; - isRunning(): boolean; - next_(): void; - results(): NestedResults; - } - - interface Matchers { - - new (env: Env, actual: any, spec: Env, isNot?: boolean): any; - - env: Env; - actual: any; - spec: Env; - isNot?: boolean; - message(): any; - - toBe(expected: any, expectationFailOutput?: any): boolean; - toEqual(expected: any, expectationFailOutput?: any): boolean; - toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; - toBeDefined(expectationFailOutput?: any): boolean; - toBeUndefined(expectationFailOutput?: any): boolean; - toBeNull(expectationFailOutput?: any): boolean; - toBeNaN(): boolean; - toBeTruthy(expectationFailOutput?: any): boolean; - toBeFalsy(expectationFailOutput?: any): boolean; - toHaveBeenCalled(): boolean; - toHaveBeenCalledWith(...params: any[]): boolean; - toHaveBeenCalledTimes(expected: number): boolean; - toContain(expected: any, expectationFailOutput?: any): boolean; - toBeLessThan(expected: number, expectationFailOutput?: any): boolean; - toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean; - toBeCloseTo(expected: number, precision: any, expectationFailOutput?: any): boolean; - toThrow(expected?: any): boolean; - toThrowError(message?: string | RegExp): boolean; - toThrowError(expected?: Error, message?: string | RegExp): boolean; - not: Matchers; - - Any: Any; - } - - interface Reporter { - reportRunnerStarting(runner: Runner): void; - reportRunnerResults(runner: Runner): void; - reportSuiteResults(suite: Suite): void; - reportSpecStarting(spec: Spec): void; - reportSpecResults(spec: Spec): void; - log(str: string): void; - } - - interface MultiReporter extends Reporter { - addReporter(reporter: Reporter): void; - } - - interface Runner { - - new (env: Env): any; - - execute(): void; - beforeEach(beforeEachFunction: SpecFunction): void; - afterEach(afterEachFunction: SpecFunction): void; - beforeAll(beforeAllFunction: SpecFunction): void; - afterAll(afterAllFunction: SpecFunction): void; - finishCallback(): void; - addSuite(suite: Suite): void; - add(block: Block): void; - specs(): Spec[]; - suites(): Suite[]; - topLevelSuites(): Suite[]; - results(): NestedResults; - } - - interface SpecFunction { - (spec?: Spec): void; - } - - interface SuiteOrSpec { - id: number; - env: Env; - description: string; - queue: Queue; - } - - interface Spec extends SuiteOrSpec { - - new (env: Env, suite: Suite, description: string): any; - - suite: Suite; - - afterCallbacks: SpecFunction[]; - spies_: Spy[]; - - results_: NestedResults; - matchersClass: Matchers; - - getFullName(): string; - results(): NestedResults; - log(arguments: any): any; - runs(func: SpecFunction): Spec; - addToQueue(block: Block): void; - addMatcherResult(result: Result): void; - expect(actual: any): any; - waits(timeout: number): Spec; - waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; - fail(e?: any): void; - getMatchersClass_(): Matchers; - addMatchers(matchersPrototype: CustomMatcherFactories): void; - finishCallback(): void; - finish(onComplete?: () => void): void; - after(doAfter: SpecFunction): void; - execute(onComplete?: () => void): any; - addBeforesAndAftersToQueue(): void; - explodes(): void; - spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; - removeAllSpies(): void; - } - - interface XSpec { - id: number; - runs(): void; - } - - interface Suite extends SuiteOrSpec { - - new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; - - parentSuite: Suite; - - getFullName(): string; - finish(onComplete?: () => void): void; - beforeEach(beforeEachFunction: SpecFunction): void; - afterEach(afterEachFunction: SpecFunction): void; - beforeAll(beforeAllFunction: SpecFunction): void; - afterAll(afterAllFunction: SpecFunction): void; - results(): NestedResults; - add(suiteOrSpec: SuiteOrSpec): void; - specs(): Spec[]; - suites(): Suite[]; - children(): any[]; - execute(onComplete?: () => void): void; - } - - interface XSuite { - execute(): void; - } - - interface Spy { - (...params: any[]): any; - - identity: string; - and: SpyAnd; - calls: Calls; - mostRecentCall: { args: any[]; }; - argsForCall: any[]; - wasCalled: boolean; - } - - interface SpyAnd { - /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ - callThrough(): Spy; - /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ - returnValue(val: any): Spy; - /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ - callFake(fn: Function): Spy; - /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ - throwError(msg: string): Spy; - /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ - stub(): Spy; - } - - interface Calls { - /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ - any(): boolean; - /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ - count(): number; - /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ - argsFor(index: number): any[]; - /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ - allArgs(): any[]; - /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ - all(): CallInfo[]; - /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ - mostRecent(): CallInfo; - /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ - first(): CallInfo; - /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ - reset(): void; - } - - interface CallInfo { - /** The context (the this) for the call */ - object: any; - /** All arguments passed to the call */ - args: any[]; - } - - interface Util { - inherit(childClass: Function, parentClass: Function): any; - formatException(e: any): any; - htmlEscape(str: string): string; - argsToArray(args: any): any; - extend(destination: any, source: any): any; - } - - interface JsApiReporter extends Reporter { - - started: boolean; - finished: boolean; - result: any; - messages: any; - - new (): any; - - suites(): Suite[]; - summarize_(suiteOrSpec: SuiteOrSpec): any; - results(): any; - resultsForSpec(specId: any): any; - log(str: any): any; - resultsForSpecs(specIds: any): any; - summarizeResult_(result: any): any; - } - - interface Jasmine { - Spec: Spec; - clock: Clock; - util: Util; - } - - export var HtmlReporter: HtmlReporter; - export var HtmlSpecFilter: HtmlSpecFilter; - export var DEFAULT_TIMEOUT_INTERVAL: number; -} +// Type definitions for Jasmine 2.2 +// Project: http://jasmine.github.io/ +// Definitions by: Boris Yankov , Theodore Brown , David Pärsson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +// For ddescribe / iit use : https://github.com/borisyankov/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts + +declare function describe(description: string, specDefinitions: () => void): void; +declare function fdescribe(description: string, specDefinitions: () => void): void; +declare function xdescribe(description: string, specDefinitions: () => void): void; + +declare function it(expectation: string, assertion?: () => void, timeout?: number): void; +declare function it(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: () => void, timeout?: number): void; +declare function fit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; +declare function xit(expectation: string, assertion?: () => void, timeout?: number): void; +declare function xit(expectation: string, assertion?: (done: () => void) => void, timeout?: number): void; + +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; + +declare function beforeEach(action: () => void, timeout?: number): void; +declare function beforeEach(action: (done: () => void) => void, timeout?: number): void; +declare function afterEach(action: () => void, timeout?: number): void; +declare function afterEach(action: (done: () => void) => void, timeout?: number): void; + +declare function beforeAll(action: () => void, timeout?: number): void; +declare function beforeAll(action: (done: () => void) => void, timeout?: number): void; +declare function afterAll(action: () => void, timeout?: number): void; +declare function afterAll(action: (done: () => void) => void, timeout?: number): void; + +declare function expect(spy: Function): jasmine.Matchers; +declare function expect(actual: any): jasmine.Matchers; + +declare function fail(e?: any): void; + +declare function spyOn(object: any, method: string): jasmine.Spy; + +declare function runs(asyncMethod: Function): void; +declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; +declare function waits(timeout?: number): void; + +declare module jasmine { + + var clock: () => Clock; + + function any(aclass: any): Any; + function anything(): Any; + function arrayContaining(sample: any[]): ArrayContaining; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function getEnv(): Env; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + function stringMatching(str: string): Any; + function stringMatching(str: RegExp): Any; + + interface Any { + + new (expectedClass: any): any; + + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface ArrayLike { + length: number; + [n: number]: T; + } + + interface ArrayContaining { + new (sample: any[]): any; + + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Block { + + new (env: Env, func: SpecFunction, spec: Spec): any; + + execute(onComplete: () => void): void; + } + + interface WaitsBlock extends Block { + new (env: Env, timeout: number, spec: Spec): any; + } + + interface WaitsForBlock extends Block { + new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; + } + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherResult { + pass: boolean; + message?: string; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface Env { + setTimeout: any; + clearTimeout: void; + setInterval: any; + clearInterval: void; + updateInterval: number; + + currentSpec: Spec; + + matchersClass: Matchers; + + version(): any; + versionString(): string; + nextSpecId(): number; + addReporter(reporter: Reporter): void; + execute(): void; + describe(description: string, specDefinitions: () => void): Suite; + // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these + beforeEach(beforeEachFunction: () => void): void; + beforeAll(beforeAllFunction: () => void): void; + currentRunner(): Runner; + afterEach(afterEachFunction: () => void): void; + afterAll(afterAllFunction: () => void): void; + xdescribe(desc: string, specDefinitions: () => void): XSuite; + it(description: string, func: () => void): Spec; + // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these + xit(desc: string, func: () => void): XSpec; + compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; + compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + contains_(haystack: any, needle: any): boolean; + addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + addMatchers(matchers: CustomMatcherFactories): void; + specFilter(spec: Spec): boolean; + } + + interface FakeTimer { + + new (): any; + + reset(): void; + tick(millis: number): void; + runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; + scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; + } + + interface HtmlReporter { + new (): any; + } + + interface HtmlSpecFilter { + new (): any; + } + + interface Result { + type: string; + } + + interface NestedResults extends Result { + description: string; + + totalCount: number; + passedCount: number; + failedCount: number; + + skipped: boolean; + + rollupCounts(result: NestedResults): void; + log(values: any): void; + getItems(): Result[]; + addResult(result: Result): void; + passed(): boolean; + } + + interface MessageResult extends Result { + values: any; + trace: Trace; + } + + interface ExpectationResult extends Result { + matcherName: string; + passed(): boolean; + expected: any; + actual: any; + message: string; + trace: Trace; + } + + interface Trace { + name: string; + message: string; + stack: any; + } + + interface PrettyPrinter { + + new (): any; + + format(value: any): void; + iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; + emitScalar(value: any): void; + emitString(value: string): void; + emitArray(array: any[]): void; + emitObject(obj: any): void; + append(value: any): void; + } + + interface StringPrettyPrinter extends PrettyPrinter { + } + + interface Queue { + + new (env: any): any; + + env: Env; + ensured: boolean[]; + blocks: Block[]; + running: boolean; + index: number; + offset: number; + abort: boolean; + + addBefore(block: Block, ensure?: boolean): void; + add(block: any, ensure?: boolean): void; + insertNext(block: any, ensure?: boolean): void; + start(onComplete?: () => void): void; + isRunning(): boolean; + next_(): void; + results(): NestedResults; + } + + interface Matchers { + + new (env: Env, actual: any, spec: Env, isNot?: boolean): any; + + env: Env; + actual: any; + spec: Env; + isNot?: boolean; + message(): any; + + toBe(expected: any, expectationFailOutput?: any): boolean; + toEqual(expected: any, expectationFailOutput?: any): boolean; + toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; + toBeDefined(expectationFailOutput?: any): boolean; + toBeUndefined(expectationFailOutput?: any): boolean; + toBeNull(expectationFailOutput?: any): boolean; + toBeNaN(): boolean; + toBeTruthy(expectationFailOutput?: any): boolean; + toBeFalsy(expectationFailOutput?: any): boolean; + toHaveBeenCalled(): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toContain(expected: any, expectationFailOutput?: any): boolean; + toBeLessThan(expected: number, expectationFailOutput?: any): boolean; + toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean; + toBeCloseTo(expected: number, precision: any, expectationFailOutput?: any): boolean; + toThrow(expected?: any): boolean; + toThrowError(message?: string | RegExp): boolean; + toThrowError(expected?: Error, message?: string | RegExp): boolean; + not: Matchers; + + Any: Any; + } + + interface Reporter { + reportRunnerStarting(runner: Runner): void; + reportRunnerResults(runner: Runner): void; + reportSuiteResults(suite: Suite): void; + reportSpecStarting(spec: Spec): void; + reportSpecResults(spec: Spec): void; + log(str: string): void; + } + + interface MultiReporter extends Reporter { + addReporter(reporter: Reporter): void; + } + + interface Runner { + + new (env: Env): any; + + execute(): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + finishCallback(): void; + addSuite(suite: Suite): void; + add(block: Block): void; + specs(): Spec[]; + suites(): Suite[]; + topLevelSuites(): Suite[]; + results(): NestedResults; + } + + interface SpecFunction { + (spec?: Spec): void; + } + + interface SuiteOrSpec { + id: number; + env: Env; + description: string; + queue: Queue; + } + + interface Spec extends SuiteOrSpec { + + new (env: Env, suite: Suite, description: string): any; + + suite: Suite; + + afterCallbacks: SpecFunction[]; + spies_: Spy[]; + + results_: NestedResults; + matchersClass: Matchers; + + getFullName(): string; + results(): NestedResults; + log(arguments: any): any; + runs(func: SpecFunction): Spec; + addToQueue(block: Block): void; + addMatcherResult(result: Result): void; + expect(actual: any): any; + waits(timeout: number): Spec; + waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; + fail(e?: any): void; + getMatchersClass_(): Matchers; + addMatchers(matchersPrototype: CustomMatcherFactories): void; + finishCallback(): void; + finish(onComplete?: () => void): void; + after(doAfter: SpecFunction): void; + execute(onComplete?: () => void): any; + addBeforesAndAftersToQueue(): void; + explodes(): void; + spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; + removeAllSpies(): void; + } + + interface XSpec { + id: number; + runs(): void; + } + + interface Suite extends SuiteOrSpec { + + new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; + + parentSuite: Suite; + + getFullName(): string; + finish(onComplete?: () => void): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + beforeAll(beforeAllFunction: SpecFunction): void; + afterAll(afterAllFunction: SpecFunction): void; + results(): NestedResults; + add(suiteOrSpec: SuiteOrSpec): void; + specs(): Spec[]; + suites(): Suite[]; + children(): any[]; + execute(onComplete?: () => void): void; + } + + interface XSuite { + execute(): void; + } + + interface Spy { + (...params: any[]): any; + + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ + all(): CallInfo[]; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + } + + interface Util { + inherit(childClass: Function, parentClass: Function): any; + formatException(e: any): any; + htmlEscape(str: string): string; + argsToArray(args: any): any; + extend(destination: any, source: any): any; + } + + interface JsApiReporter extends Reporter { + + started: boolean; + finished: boolean; + result: any; + messages: any; + + new (): any; + + suites(): Suite[]; + summarize_(suiteOrSpec: SuiteOrSpec): any; + results(): any; + resultsForSpec(specId: any): any; + log(str: any): any; + resultsForSpecs(specIds: any): any; + summarizeResult_(result: any): any; + } + + interface Jasmine { + Spec: Spec; + clock: Clock; + util: Util; + } + + export var HtmlReporter: HtmlReporter; + export var HtmlSpecFilter: HtmlSpecFilter; + export var DEFAULT_TIMEOUT_INTERVAL: number; +} diff --git a/knockout.mapping/knockout.mapping-tests.ts b/knockout.mapping/knockout.mapping-tests.ts index 85e37a4a5..bac7aac00 100644 --- a/knockout.mapping/knockout.mapping-tests.ts +++ b/knockout.mapping/knockout.mapping-tests.ts @@ -57,7 +57,7 @@ mapping.fromJS(inputJSON, { return mapping.fromJS(options.data); }, update: (options: KnockoutMappingUpdateOptions) => { - return mapping.fromJS(options.data, options.target); + return mapping.fromJS(options.data, options.target); } } }); diff --git a/knockout.mapping/knockout.mapping.d.ts b/knockout.mapping/knockout.mapping.d.ts index d1a35d3ee..78127570d 100644 --- a/knockout.mapping/knockout.mapping.d.ts +++ b/knockout.mapping/knockout.mapping.d.ts @@ -1,68 +1,68 @@ -// Type definitions for Knockout.Mapping 2.0 -// Project: https://github.com/SteveSanderson/knockout.mapping -// Definitions by: Boris Yankov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -interface KnockoutMappingCreateOptions { - data: any; - parent: any; -} - -interface KnockoutMappingUpdateOptions { - data: any; - parent: any; - target: any; - observable?: KnockoutObservable; -} - -interface KnockoutMappingOptions { - ignore?: string[]; - include?: string[]; - copy?: string[]; - mappedProperties?: string[]; - deferEvaluation?: boolean; - create?: (options: KnockoutMappingCreateOptions) => void; - update?: (options: KnockoutMappingUpdateOptions) => void; - key?: (data: any) => any; -} - -interface KnockoutMapping { - isMapped(viewModel: any): boolean; - fromJS(jsObject: any): any; - fromJS(jsObject: any, targetOrOptions: any): any; - fromJS(jsObject: any, inputOptions: any, target: any): any; - fromJSON(jsonString: string): any; - fromJSON(jsonString: string, targetOrOptions: any): any; - fromJSON(jsonString: string, inputOptions: any, target: any): any; - toJS(rootObject: any, options?: KnockoutMappingOptions): any; - toJSON(rootObject: any, options?: KnockoutMappingOptions): any; - defaultOptions(): KnockoutMappingOptions; - resetDefaultOptions(): void; - getType(x: any): any; - visitModel(rootObject: any, callback: Function, options?: { visitedObjects?: any; parentName?: string; ignore?: string[]; copy?: string[]; include?: string[]; }): any; -} - -interface KnockoutObservableArrayFunctions { - mappedCreate(item: T): T; - - mappedRemove(item: T): T[]; - mappedRemove(removeFunction: (item: T) => boolean): T[]; - mappedRemoveAll(items: T[]): T[]; - mappedRemoveAll(): T[]; - - mappedDestroy(item: T): void; - mappedDestroy(destroyFunction: (item: T) => boolean): void; - mappedDestroyAll(items: T[]): void; - mappedDestroyAll(): void; -} - -interface KnockoutStatic { - mapping: KnockoutMapping; -} - -declare module "knockout.mapping" { - export = mapping; -} -declare var mapping: KnockoutMapping; +// Type definitions for Knockout.Mapping 2.0 +// Project: https://github.com/SteveSanderson/knockout.mapping +// Definitions by: Boris Yankov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface KnockoutMappingCreateOptions { + data: any; + parent: any; +} + +interface KnockoutMappingUpdateOptions { + data: any; + parent: any; + target: any; + observable?: KnockoutObservable; +} + +interface KnockoutMappingOptions { + ignore?: string[]; + include?: string[]; + copy?: string[]; + mappedProperties?: string[]; + deferEvaluation?: boolean; + create?: (options: KnockoutMappingCreateOptions) => void; + update?: (options: KnockoutMappingUpdateOptions) => void; + key?: (data: any) => any; +} + +interface KnockoutMapping { + isMapped(viewModel: any): boolean; + fromJS(jsObject: any): any; + fromJS(jsObject: any, targetOrOptions: any): any; + fromJS(jsObject: any, inputOptions: any, target: any): any; + fromJSON(jsonString: string): any; + fromJSON(jsonString: string, targetOrOptions: any): any; + fromJSON(jsonString: string, inputOptions: any, target: any): any; + toJS(rootObject: any, options?: KnockoutMappingOptions): any; + toJSON(rootObject: any, options?: KnockoutMappingOptions): any; + defaultOptions(): KnockoutMappingOptions; + resetDefaultOptions(): void; + getType(x: any): any; + visitModel(rootObject: any, callback: Function, options?: { visitedObjects?: any; parentName?: string; ignore?: string[]; copy?: string[]; include?: string[]; }): any; +} + +interface KnockoutObservableArrayFunctions { + mappedCreate(item: T): T; + + mappedRemove(item: T): T[]; + mappedRemove(removeFunction: (item: T) => boolean): T[]; + mappedRemoveAll(items: T[]): T[]; + mappedRemoveAll(): T[]; + + mappedDestroy(item: T): void; + mappedDestroy(destroyFunction: (item: T) => boolean): void; + mappedDestroyAll(items: T[]): void; + mappedDestroyAll(): void; +} + +interface KnockoutStatic { + mapping: KnockoutMapping; +} + +declare module "knockout.mapping" { + export = mapping; +} +declare var mapping: KnockoutMapping; diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index ef02c29d2..fd696b2a5 100755 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,4356 +1,4356 @@ -// Type definitions for Leaflet.js 0.7.3 -// Project: https://github.com/Leaflet/Leaflet -// Definitions by: Vladimir Zotov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module L { - type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) - type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; -} - -declare module L { - - export interface AttributionOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomright'. - */ - position?: string; - - /** - * The HTML text shown before the attributions. Pass false to disable. - * Default value: 'Powered by Leaflet'. - */ - prefix?: string; - - } -} - -declare module L { - - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - export function bounds(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - export function bounds(points: Point[]): Bounds; - - - export interface BoundsStatic { - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - new(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - new(points: Point[]): Bounds; - } - export var Bounds: BoundsStatic; - - export interface Bounds { - /** - * Extends the bounds to contain the given point. - */ - extend(point: Point): void; - - /** - * Returns the center point of the bounds. - */ - getCenter(): Point; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: Bounds): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(point: Point): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: Bounds): boolean; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; - - /** - * Returns the size of the given bounds. - */ - getSize(): Point; - - /** - * The top left corner of the rectangle. - */ - min: Point; - - /** - * The bottom right corner of the rectangle. - */ - max: Point; - } -} - -declare module L { - - module Browser { - - /** - * true for all Internet Explorer versions. - */ - export var ie: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie6: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie7: boolean; - - /** - * true for webkit-based browsers like Chrome and Safari (including mobile - * versions). - */ - export var webkit: boolean; - - /** - * true for webkit-based browsers that support CSS 3D transformations. - */ - export var webkit3d: boolean; - - /** - * true for Android mobile browser. - */ - export var android: boolean; - - /** - * true for old Android stock browsers (2 and 3). - */ - export var android23: boolean; - - /** - * true for modern mobile browsers (including iOS Safari and different Android - * browsers). - */ - export var mobile: boolean; - - /** - * true for mobile webkit-based browsers. - */ - export var mobileWebkit: boolean; - - /** - * true for mobile Opera. - */ - export var mobileOpera: boolean; - - /** - * true for all browsers on touch devices. - */ - export var touch: boolean; - - /** - * true for browsers with Microsoft touch model (e.g. IE10). - */ - export var msTouch: boolean; - - /** - * true for devices with Retina screens. - */ - export var retina: boolean; - - } -} - - -declare module L { - - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - - export interface CircleStatic extends ClassStatic { - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - } - export var Circle: CircleStatic; - - export interface Circle extends Path { - /** - * Returns the current geographical position of the circle. - */ - getLatLng(): LatLng; - - /** - * Returns the current radius of a circle. Units are in meters. - */ - getRadius(): number; - - /** - * Sets the position of a circle to a new location. - */ - setLatLng(latlng: LatLngExpression): Circle; - - /** - * Sets the radius of a circle. Units are in meters. - */ - setRadius(radius: number): Circle; - - /** - * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). - */ - toGeoJSON(): any; - - } -} - -declare module L { - - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - - - export interface CircleMarkerStatic extends ClassStatic { - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - } - export var CircleMarker: CircleMarkerStatic; - - export interface CircleMarker extends Circle { - /** - * Sets the position of a circle marker to a new location. - */ - setLatLng(latlng: LatLngExpression): CircleMarker; - - /** - * Sets the radius of a circle marker. Units are in pixels. - */ - setRadius(radius: number): CircleMarker; - - /** - * Returns a GeoJSON representation of the circle marker (GeoJSON Point Feature). - */ - toGeoJSON(): any; - } -} - -declare module L { - export interface ClassExtendOptions { - /** - * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. - */ - initialize?: Function; - - /** - * options is a special property that unlike other objects that you pass - * to extend will be merged with the parent one instead of overriding it - * completely, which makes managing configuration of objects and default - * values convenient. - */ - options?: any; - - /** - * includes is a special class property that merges all specified objects - * into the class (such objects are called mixins). A good example of this - * is L.Mixin.Events that event-related methods like on, off and fire - * to the class. - */ - includes?: any; - - /** - * statics is just a convenience property that injects specified object - * properties as the static properties of the class, useful for defining - * constants. - */ - static?: any; - - [prop: string]: any; - } - - export interface ClassStatic { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - extend(options: ClassExtendOptions): any; - extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; - - /** - * You can also use the following shortcut when you just need to make - * one additional method call. - */ - addInitHook(methodName: string, ...args: any[]): void; - } - - - /** - * L.Class powers the OOP facilities of Leaflet and is used to create - * almost all of the Leaflet classes documented. - */ - module Class { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - function extend(options: ClassExtendOptions): any; - } - -} - -declare module L { - export interface ControlStatic extends ClassStatic { - /** - * Creates a control with the given options. - */ - new(options?: ControlOptions): Control; - - Zoom: Control.ZoomStatic; - Attribution: Control.AttributionStatic; - Layers: Control.LayersStatic; - Scale: Control.ScaleStatic; - } - export var Control: ControlStatic; - - export interface Control extends IControl { - /** - * Sets the position of the control. See control positions. - */ - setPosition(position: string): Control; - - /** - * Returns the current position of the control. - */ - getPosition(): string; - - /** - * Adds the control to the map. - */ - addTo(map: Map): Control; - - /** - * Removes the control from the map. - */ - removeFrom(map: Map): Control; - - /** - * Returns the HTML container of the control. - */ - getContainer(): HTMLElement; - - // IControl members - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } - - namespace Control { - export interface ZoomStatic extends ClassStatic { - /** - * Creates a zoom control. - */ - new (options?: ZoomOptions): Zoom; - } - - export interface Zoom extends L.Control { - } - - export interface ZoomOptions { - /** - * The position of the control (one of the map corners). - * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. - * - * Default value: 'topright'. - */ - position?: string; // 'topleft' | 'topright' | 'bottomleft' | 'bottomright' - - /** - * The text set on the zoom in button. - * - * Default value: '+' - */ - zoomInText?: string; - - /** - * The text set on the zoom out button. - * - * Default value: '-' - */ - zoomOutText?: string; - - /** - * The title set on the zoom in button. - * - * Default value: 'Zoom in' - */ - zoomInTitle?: string; - - /** - * The title set on the zoom out button. - * - * Default value: 'Zoom out' - */ - zoomOutTitle?: string; - } - - export interface AttributionStatic extends ClassStatic { - /** - * Creates an attribution control. - */ - new(options?: AttributionOptions): Attribution; - } - - export interface Attribution extends L.Control { - /** - * Sets the text before the attributions. - */ - setPrefix(prefix: string): Attribution; - - /** - * Adds an attribution text (e.g. 'Vector data © CloudMade'). - */ - addAttribution(text: string): Attribution; - - /** - * Removes an attribution text. - */ - removeAttribution(text: string): Attribution; - - } - - export interface LayersStatic extends ClassStatic { - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; - } - - export interface Layers extends L.Control, IEventPowered { - /** - * Adds a base layer (radio button entry) with the given name to the control. - */ - addBaseLayer(layer: ILayer, name: string): Layers; - - /** - * Adds an overlay (checkbox entry) with the given name to the control. - */ - addOverlay(layer: ILayer, name: string): Layers; - - /** - * Remove the given layer from the control. - */ - removeLayer(layer: ILayer): Layers; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Layers; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - fire(type: string, data?: any): Layers; - addEventListener(eventMap: any, context?: any): Layers; - removeEventListener(eventMap?: any, context?: any): Layers; - clearAllEventListeners(): Layers; - on(eventMap: any, context?: any): Layers; - off(eventMap?: any, context?: any): Layers; - } - - export interface ScaleStatic extends ClassStatic { - /** - * Creates an scale control with the given options. - */ - new(options?: ScaleOptions): Scale; - } - - export interface Scale extends L.Control { - } - } - - export interface control { - /** - * Creates a control with the given options. - */ - (options?: ControlOptions): Control; - } - - export namespace control { - - /** - * Creates a zoom control. - */ - export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; - - /** - * Creates an attribution control. - */ - export function attribution(options?: AttributionOptions): L.Control.Attribution; - - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; - - /** - * Creates an scale control with the given options. - */ - export function scale(options?: ScaleOptions): L.Control.Scale; - } -} - -declare namespace L { - - export interface ControlOptions { - - /** - * The initial position of the control (one of the map corners). See control - * positions. - * Default value: 'topright'. - */ - position?: string; - - } -} - -declare namespace L { - - namespace CRS { - - /** - * The most common CRS for online maps, used by almost all free and commercial - * tile providers. Uses Spherical Mercator projection. Set in by default in - * Map's crs option. - */ - export var EPSG3857: ICRS; - - /** - * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. - */ - export var EPSG4326: ICRS; - - /** - * Rarely used by some commercial tile providers. Uses Elliptical Mercator - * projection. - */ - export var EPSG3395: ICRS; - - /** - * A simple CRS that maps longitude and latitude into x and y directly. May be - * used for maps of flat surfaces (e.g. game maps). Note that the y axis should - * still be inverted (going from bottom to top). - */ - export var Simple: ICRS; - - } -} - -declare namespace L { - - /** - * Creates a div icon instance with the given options. - */ - function divIcon(options: DivIconOptions): DivIcon; - - export interface DivIconStatic extends ClassStatic { - /** - * Creates a div icon instance with the given options. - */ - new(options: DivIconOptions): DivIcon; - } - export var DivIcon: DivIconStatic; - - export interface DivIcon extends Icon { - } -} - -declare namespace L { - - export interface DivIconOptions { - - /** - * Size of the icon in pixels. Can be also set through CSS. - */ - iconSize?: Point; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point; - - /** - * A custom class name to assign to the icon. - * - * Default value: 'leaflet-div-icon'. - */ - className?: string; - - /** - * A custom HTML code to put inside the div element. - * - * Default value: ''. - */ - html?: string; - - } -} - -declare namespace L { - - export interface DomEvent { - - /** - * Adds a listener fn to the element's DOM event of the specified type. this keyword - * inside the listener will point to context, or to the element if not specified. - */ - addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Removes an event listener from the element. - */ - removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Stop the given event from propagation to parent elements. Used inside the - * listener functions: - * L.DomEvent.addListener(div, 'click', function - * (e) { - * L.DomEvent.stopPropagation(e); - * }); - */ - stopPropagation(e: Event): DomEvent; - - /** - * Prevents the default action of the event from happening (such as following - * a link in the href of the a element, or doing a POST request with page reload - * when form is submitted). Use it inside listener functions. - */ - preventDefault(e: Event): DomEvent; - - /** - * Does stopPropagation and preventDefault at the same time. - */ - stop(e: Event): DomEvent; - - /** - * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' - * and 'touchstart' events. - */ - disableClickPropagation(el: HTMLElement): DomEvent; - - /** - * Gets normalized mouse position from a DOM event relative to the container - * or to the whole page if not specified. - */ - getMousePosition(e: Event, container?: HTMLElement): Point; - - /** - * Gets normalized wheel delta from a mousewheel DOM event. - */ - getWheelDelta(e: Event): number; - - } - - export var DomEvent: DomEvent; -} - -declare namespace L { - - namespace DomUtil { - - /** - * Returns an element with the given id if a string was passed, or just returns - * the element if it was passed directly. - */ - export function get(id: string): HTMLElement; - - /** - * Returns the value for a certain style attribute on an element, including - * computed values or values set through CSS. - */ - export function getStyle(el: HTMLElement, style: string): string; - - /** - * Returns the offset to the viewport for the requested element. - */ - export function getViewportOffset(el: HTMLElement): Point; - - /** - * Creates an element with tagName, sets the className, and optionally appends - * it to container element. - */ - export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; - - /** - * Makes sure text cannot be selected, for example during dragging. - */ - export function disableTextSelection(): void; - - /** - * Makes text selection possible again. - */ - export function enableTextSelection(): void; - - /** - * Returns true if the element class attribute contains name. - */ - export function hasClass(el: HTMLElement, name: string): boolean; - - /** - * Adds name to the element's class attribute. - */ - export function addClass(el: HTMLElement, name: string): void; - - /** - * Removes name from the element's class attribute. - */ - export function removeClass(el: HTMLElement, name: string): void; - - /** - * Set the opacity of an element (including old IE support). Value must be from - * 0 to 1. - */ - export function setOpacity(el: HTMLElement, value: number): void; - - /** - * Goes through the array of style names and returns the first name that is a valid - * style name for an element. If no such name is found, it returns false. Useful - * for vendor-prefixed styles like transform. - */ - export function testProp(props: string[]): any; - - /** - * Returns a CSS transform string to move an element by the offset provided in - * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms - * and 2D on other browsers. - */ - export function getTranslateString(point: Point): string; - - /** - * Returns a CSS transform string to scale an element (with the given scale origin). - */ - export function getScaleString(scale: number, origin: Point): string; - - /** - * Sets the position of an element to coordinates specified by point, using - * CSS translate or top/left positioning depending on the browser (used by - * Leaflet internally to position its layers). Forces top/left positioning - * if disable3D is true. - */ - export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; - - /** - * Returns the coordinates of an element previously positioned with setPosition. - */ - export function getPosition(el: HTMLElement): Point; - - /** - * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). - */ - export var TRANSITION: string; - - /** - * Vendor-prefixed transform style name. - */ - export var TRANSFORM: string; - - } -} - -declare namespace L { - export interface DraggableStatic extends ClassStatic { - /** - * Creates a Draggable object for moving the given element when you start dragging - * the dragHandle element (equals the element itself by default). - */ - new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; - } - export var Draggable: DraggableStatic; - - - export interface Draggable extends IEventPowered { - /** - * Enables the dragging ability. - */ - enable(): void; - - /** - * Disables the dragging ability. - */ - disable(): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Draggable; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - fire(type: string, data?: any): Draggable; - addEventListener(eventMap: any, context?: any): Draggable; - removeEventListener(eventMap?: any, context?: any): Draggable; - clearAllEventListeners(): Draggable; - on(eventMap: any, context?: any): Draggable; - off(eventMap?: any, context?: any): Draggable; - } -} - - - -declare namespace L { - - /** - * Create a layer group, optionally given an initial set of layers. - */ - function featureGroup(layers?: T[]): FeatureGroup; - - - export interface FeatureGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): FeatureGroup; - } - export var FeatureGroup: FeatureGroupStatic; - - export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { - /** - * Binds a popup with a particular HTML content to a click on any layer from the - * group that has a bindPopup method. - */ - bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; - - /** - * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates - * of its children). - */ - getBounds(): LatLngBounds; - - /** - * Sets the given path options to each layer of the group that has a setStyle method. - */ - setStyle(style: PathOptions): FeatureGroup; - - /** - * Brings the layer group to the top of all other layers. - */ - bringToFront(): FeatureGroup; - - /** - * Brings the layer group to the bottom of all other layers. - */ - bringToBack(): FeatureGroup; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): FeatureGroup; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - fire(type: string, data?: any): FeatureGroup; - addEventListener(eventMap: any, context?: any): FeatureGroup; - removeEventListener(eventMap?: any, context?: any): FeatureGroup; - clearAllEventListeners(): FeatureGroup; - on(eventMap: any, context?: any): FeatureGroup; - off(eventMap?: any, context?: any): FeatureGroup; - } -} - -declare namespace L { - - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - export interface GeoJSONStatic extends ClassStatic { - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - new(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - /** - * Creates a layer from a given GeoJSON feature. - */ - geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; - - /** - * Creates a LatLng object from an array of 2 numbers (latitude, longitude) - * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted - * as (longitude, latitude). - */ - coordsToLatLng(coords: number[], reverse?: boolean): LatLng; - - /** - * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates - * array. levelsDeep specifies the nesting level (0 is for an array of points, - * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to - * true, the numbers will be interpreted as (longitude, latitude). - */ - coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; - } - export var GeoJSON: GeoJSONStatic; - - export interface GeoJSON extends FeatureGroup { - /** - * Adds a GeoJSON object to the layer. - */ - addData(data: any): boolean; - - /** - * Changes styles of GeoJSON vector layers with the given style function. - */ - setStyle(style: (featureData: any) => any): GeoJSON; - - /** - * Changes styles of GeoJSON vector layers with the given style options. - */ - setStyle(style: PathOptions): GeoJSON; - - /** - * Resets the the given vector layer's style to the original GeoJSON style, - * useful for resetting style after hover events. - */ - resetStyle(layer: Path): GeoJSON; - } -} - -declare namespace L { - export interface GeoJSONOptions { - /** - * Function that will be used for creating layers for GeoJSON points (if not - * specified, simple markers will be created). - */ - pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; - - /** - * Function that will be used to get style options for vector layers created - * for GeoJSON features. - */ - style?: (featureData: any) => any; - - /** - * Function that will be called on each created feature layer. Useful for attaching - * events and popups to features. - */ - onEachFeature?: (featureData: any, layer: ILayer) => void; - - /** - * Function that will be used to decide whether to show a feature or not. - */ - filter?: (featureData: any, layer: ILayer) => boolean; - - /** - * Function that will be used for converting GeoJSON coordinates to LatLng points - * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] - * values in degrees). - */ - coordsToLatLng?: (coords: any[]) => LatLng[]; - } -} - - - - -declare namespace L { - - /** - * Creates an icon instance with the given options. - */ - function icon(options: IconOptions): Icon; - - export interface IconStatic extends ClassStatic { - /** - * Creates an icon instance with the given options. - */ - new(options: IconOptions): Icon; - - Default: { - /** - * Creates a default icon instance with the given options. - */ - new(options?: IconOptions): Icon.Default; - - imagePath: string; - }; - } - export var Icon: IconStatic; - - export interface Icon { - } - - namespace Icon { - /** - * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses - * for markers by default. - */ - export interface Default extends Icon { - } - } -} - -declare namespace L { - - export interface IconOptions { - - /** - * (required) The URL to the icon image (absolute or relative to your script - * path). - */ - iconUrl?: string; - - /** - * The URL to a retina sized version of the icon image (absolute or relative to - * your script path). Used for Retina screen devices. - */ - iconRetinaUrl?: string; - - /** - * Size of the icon image in pixels. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * The URL to the icon shadow image. If not specified, no shadow image will be - * created. - */ - shadowUrl?: string; - - /** - * The URL to the retina sized version of the icon shadow image. If not specified, - * no shadow image will be created. Used for Retina screen devices. - */ - shadowRetinaUrl?: string; - - /** - * Size of the shadow image in pixels. - */ - shadowSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the shadow (relative to its top left corner) - * (the same as iconAnchor if not specified). - */ - shadowAnchor?: Point|[number, number]; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to both icon and shadow images. Empty by default. - */ - className?: string; - } -} - -declare namespace L { - - export interface IControl { - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ICRS { - - /** - * Projection that this CRS uses. - */ - projection: IProjection; - - /** - * Transformation that this CRS uses to turn projected coordinates into screen - * coordinates for a particular tile service. - */ - transformation: Transformation; - - /** - * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). - */ - code: string; - - /** - * Projects geographical coordinates on a given zoom into pixel coordinates. - */ - latLngToPoint(latlng: LatLng, zoom: number): Point; - - /** - * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom - * into geographical coordinates. - */ - pointToLatLng(point: Point, zoom: number): LatLng; - - /** - * Projects geographical coordinates into coordinates in units accepted - * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). - */ - project(latlng: LatLng): Point; - - /** - * Returns the scale used when transforming projected coordinates into pixel - * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for - * Mercator-based CRS. - */ - scale(zoom: number): number; - - /** - * Returns the size of the world in pixels for a particular zoom. - */ - getSize(zoom: number): Point; - - } -} - -declare namespace L { - - export interface IEventPowered { - - /** - * Adds a listener function (fn) to a particular event type of the object. You - * can optionally specify the context of the listener (object the this keyword - * will point to). You can also pass several space-separated types (e.g. 'click - * dblclick'). - */ - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * The same as above except the listener will only get fired once and then removed. - */ - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - /** - * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} - */ - addEventListener(eventMap: any, context?: any): T; - - /** - * Removes a previously added listener function. If no function is specified, - * it will remove all the listeners of that particular event from the object. - */ - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Removes a set of type/listener pairs. - */ - removeEventListener(eventMap?: any, context?: any): T; - - /** - * Returns true if a particular event type has some listeners attached to it. - */ - hasEventListeners(type: string): boolean; - - /** - * Fires an event of the specified type. You can optionally provide an data object - * — the first argument of the listener function will contain its properties. - */ - fireEvent(type: string, data?: any): T; - - /** - * Removes all listeners to all events on the object. - */ - clearAllEventListeners(): T; - - /** - * Alias to addEventListener. - */ - on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to addEventListener. - */ - on(eventMap: any, context?: any): T; - - /** - * Alias to addOneTimeEventListener. - */ - once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(eventMap?: any, context?: any): T; - - /** - * Alias to fireEvent. - */ - fire(type: string, data?: any): T; - } -} - -declare namespace L { - - export interface IHandler { - - /** - * Enables the handler. - */ - enable(): void; - - /** - * Disables the handler. - */ - disable(): void; - - /** - * Returns true if the handler is enabled. - */ - enabled(): boolean; - } - - export interface Handler { - initialize(map: Map): void; - } -} - -declare namespace L { - - export interface ILayer { - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - namespace Mixin { - export interface LeafletMixinEvents extends IEventPowered { - } - - export var Events: LeafletMixinEvents; - } -} - -declare namespace L { - - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - - export interface ImageOverlayStatic extends ClassStatic { - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - } - export var ImageOverlay: ImageOverlayStatic; - - export interface ImageOverlay extends ILayer { - /** - * Adds the overlay to the map. - */ - addTo(map: Map): ImageOverlay; - - /** - * Sets the opacity of the overlay. - */ - setOpacity(opacity: number): ImageOverlay; - - /** - * Changes the URL of the image. - */ - setUrl(imageUrl: string): ImageOverlay; - - /** - * Brings the layer to the top of all overlays. - */ - bringToFront(): ImageOverlay; - - /** - * Brings the layer to the bottom of all overlays. - */ - bringToBack(): ImageOverlay; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ImageOverlayOptions { - - /** - * The opacity of the image overlay. - */ - opacity?: number; - } -} - -declare namespace L { - - export interface IProjection { - - /** - * Projects geographical coordinates into a 2D point. - */ - project(latlng: LatLng): Point; - - /** - * The inverse of project. Projects a 2D point into geographical location. - */ - unproject(point: Point): LatLng; - } -} - -declare namespace L { - - /** - * A constant that represents the Leaflet version in use. - */ - export var version: string; - - /** - * This method restores the L global variale to the original value it had - * before Leaflet inclusion, and returns the real Leaflet namespace. - */ - export function noConflict(): typeof L; -} - -declare namespace L { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(coords: LatLngExpression): LatLng; - - export interface LatLngStatic { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(coords: LatLngExpression): LatLng; - - /** - * A multiplier for converting degrees into radians. - * - * Value: Math.PI / 180. - */ - DEG_TO_RAD: number; - - /** - * A multiplier for converting radians into degrees. - * - * Value: 180 / Math.PI. - */ - RAD_TO_DEG: number; - - /** - * Max margin of error for the equality check. - * - * Value: 1.0E-9. - */ - MAX_MARGIN: number; - } - export var LatLng: LatLngStatic; - - export interface LatLng { - /** - * Returns the distance (in meters) to the given LatLng calculated using the - * Haversine formula. See description on wikipedia - */ - distanceTo(otherLatlng: LatLngExpression): number; - - /** - * Returns true if the given LatLng point is at the same position (within a small - * margin of error). - */ - equals(otherLatlng: LatLngExpression): boolean; - - /** - * Returns a string representation of the point (for debugging purposes). - */ - toString(): string; - - /** - * Returns a new LatLng object with the longitude wrapped around left and right - * boundaries (-180 to 180 by default). - */ - wrap(left: number, right: number): LatLng; - - /** - * Latitude in degrees. - */ - lat: number; - - /** - * Longitude in degrees. - */ - lng: number; - } -} - -declare namespace L { - - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; - - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; - - export interface LatLngBoundsStatic { - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; - - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - new(latlngs: LatLngBoundsExpression): LatLngBounds; - } - export var LatLngBounds: LatLngBoundsStatic; - - export interface LatLngBounds { - /** - * Extends the bounds to contain the given point. - */ - extend(latlng: LatLngExpression): LatLngBounds; - - /** - * Extends the bounds to contain the given bounds. - */ - extend(latlng: LatLngBoundsExpression): LatLngBounds; - - /** - * Returns the south-west point of the bounds. - */ - getSouthWest(): LatLng; - - /** - * Returns the north-east point of the bounds. - */ - getNorthEast(): LatLng; - - /** - * Returns the north-west point of the bounds. - */ - getNorthWest(): LatLng; - - /** - * Returns the south-east point of the bounds. - */ - getSouthEast(): LatLng; - - /** - * Returns the west longitude in degrees of the bounds. - */ - getWest(): number; - - /** - * Returns the east longitude in degrees of the bounds. - */ - getEast(): number; - - /** - * Returns the north latitude in degrees of the bounds. - */ - getNorth(): number; - - /** - * Returns the south latitude in degrees of the bounds. - */ - getSouth(): number; - - /** - * Returns the center point of the bounds. - */ - getCenter(): LatLng; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(latlng: LatLngExpression): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle is equivalent (within a small margin of error) - * to the given bounds. - */ - equals(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' - * format. Useful for sending requests to web services that return geo data. - */ - toBBoxString(): string; - - /** - * Returns bigger bounds created by extending the current bounds by a given - * percentage in each direction. - */ - pad(bufferRatio: number): LatLngBounds; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; - - } -} - -declare namespace L { - - /** - * Create a layer group, optionally given an initial set of layers. - */ - function layerGroup(layers?: T[]): LayerGroup; - - - export interface LayerGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): LayerGroup; - } - export var LayerGroup: LayerGroupStatic; - - export interface LayerGroup extends ILayer { - /** - * Adds the group of layers to the map. - */ - addTo(map: Map): LayerGroup; - - /** - * Adds a given layer to the group. - */ - addLayer(layer: T): LayerGroup; - - /** - * Removes a given layer from the group. - */ - removeLayer(layer: T): LayerGroup; - - /** - * Removes a given layer of the given id from the group. - */ - removeLayer(id: string): LayerGroup; - - /** - * Returns true if the given layer is currently added to the group. - */ - hasLayer(layer: T): boolean; - - /** - * Returns the layer with the given id. - */ - getLayer(id: string): T; - - /** - * Returns an array of all the layers added to the group. - */ - getLayers(): T[]; - - /** - * Removes all the layers from the group. - */ - clearLayers(): LayerGroup; - - /** - * Iterates over the layers of the group, optionally specifying context of - * the iterator function. - */ - eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; - - /** - * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). - */ - toGeoJSON(): any; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - - -declare namespace L { - - export interface LayersOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * - * Default value: 'topright'. - */ - position?: string; - - /** - * If true, the control will be collapsed into an icon and expanded on mouse hover - * or touch. - * - * Default value: true. - */ - collapsed?: boolean; - - /** - * If true, the control will assign zIndexes in increasing order to all of its - * layers so that the order is preserved when switching them on/off. - * - * Default value: true. - */ - autoZIndex?: boolean; - - } -} - -declare namespace L { - - export interface LeafletErrorEvent extends LeafletEvent { - - /** - * Error message. - */ - message: string; - - /** - * Error code (if applicable). - */ - code: number; - } -} - -declare namespace L { - - export interface LeafletEvent { - - /** - * The event type (e.g. 'click'). - */ - type: string; - - /** - * The object that fired the event. - */ - target: any; - } -} - -declare namespace L { - - export interface LeafletGeoJSONEvent extends LeafletEvent { - - /** - * The layer for the GeoJSON feature that is being added to the map. - */ - layer: ILayer; - - /** - * GeoJSON properties of the feature. - */ - properties: any; - - /** - * GeoJSON geometry type of the feature. - */ - geometryType: string; - - /** - * GeoJSON ID of the feature (if present). - */ - id: string; - } -} - -declare namespace L { - - export interface LeafletLayerEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - } -} - -declare namespace L { - - export interface LeafletLayersControlEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - - /** - * The name of the layer that was added or removed. - */ - name: string; - } -} - -declare module L { - - export interface LeafletLocationEvent extends LeafletEvent { - - /** - * Detected geographical location of the user. - */ - latlng: LatLng; - - /** - * Geographical bounds of the area user is located in (with respect to the accuracy - * of location). - */ - bounds: LatLngBounds; - - /** - * Accuracy of location in meters. - */ - accuracy: number; - - /** - * Height of the position above the WGS84 ellipsoid in meters. - */ - altitude: number; - - /** - * Accuracy of altitude in meters. - */ - altitudeAccuracy: number; - - /** - * The direction of travel in degrees counting clockwise from true North. - */ - heading: number; - - /** - * Current velocity in meters per second. - */ - speed: number; - - /** - * The time when the position was acquired. - */ - timestamp: number; - - } -} - -declare namespace L { - - export interface LeafletMouseEvent extends LeafletEvent { - - /** - * The geographical point where the mouse event occured. - */ - latlng: LatLng; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map layer. - */ - layerPoint: Point; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map сontainer. - */ - containerPoint: Point; - - /** - * The original DOM mouse event fired by the browser. - */ - originalEvent: MouseEvent; - } -} - -declare namespace L { - - export interface LeafletPopupEvent extends LeafletEvent { - - /** - * The popup that was opened or closed. - */ - popup: Popup; - } -} - -declare namespace L { - - export interface LeafletDragEndEvent extends LeafletEvent { - - /** - * The distance in pixels the draggable element was moved by. - */ - distance: number; - } -} - -declare namespace L { - - export interface LeafletResizeEvent extends LeafletEvent { - - /** - * The old size before resize event. - */ - oldSize: Point; - - /** - * The new size after the resize event. - */ - newSize: Point; - } -} - -declare namespace L { - - export interface LeafletTileEvent extends LeafletEvent { - - /** - * The tile element (image). - */ - tile: HTMLElement; - - /** - * The source URL of the tile. - */ - url: string; - } -} - -declare namespace L { - - namespace LineUtil { - - /** - * Dramatically reduces the number of points in a polyline while retaining - * its shape and returns a new array of simplified points. Used for a huge performance - * boost when processing/displaying Leaflet polylines for each zoom level - * and also reducing visual noise. tolerance affects the amount of simplification - * (lesser value means higher quality but slower and with more points). Also - * released as a separated micro-library Simplify.js. - */ - export function simplify(points: Point[], tolerance: number): Point[]; - - /** - * Returns the distance between point p and segment p1 to p2. - */ - export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - - /** - * Returns the closest point from a point p on a segment p1 to p2. - */ - export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; - - /** - * Clips the segment a to b by rectangular bounds (modifying the segment points - * directly!). Used by Leaflet to only show polyline points that are on the screen - * or near, increasing performance. - */ - export function clipSegment(a: Point, b: Point, bounds: Bounds): void; - - } -} - -declare namespace L { - - export interface LocateOptions { - - /** - * If true, starts continous watching of location changes (instead of detecting - * it once) using W3C watchPosition method. You can later stop watching using - * map.stopLocate() method. - * - * Default value: false. - */ - watch?: boolean; - - /** - * If true, automatically sets the map view to the user location with respect - * to detection accuracy, or to world view if geolocation failed. - * - * Default value: false. - */ - setView?: boolean; - - /** - * The maximum zoom for automatic view setting when using `setView` option. - * - * Default value: Infinity. - */ - maxZoom?: number; - - /** - * Number of millisecond to wait for a response from geolocation before firing - * a locationerror event. - * - * Default value: 10000. - */ - timeout?: number; - - /** - * Maximum age of detected location. If less than this amount of milliseconds - * passed since last geolocation response, locate will return a cached location. - * - * Default value: 0. - */ - maximumAge?: number; - - /** - * Enables high accuracy, see description in the W3C spec. - * - * Default value: false. - */ - enableHighAccuracy?: boolean; - } -} - -declare namespace L { - - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - */ - function map(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - */ - function map(id: string, options?: Map.MapOptions): Map; - - - export interface MapStatic extends ClassStatic { - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: string, options?: Map.MapOptions): Map; - } - export var Map: MapStatic; - - export interface Map extends IEventPowered { - // Methods for Modifying Map State - - /** - * Sets the view of the map (geographical center and zoom) with the given - * animation options. - */ - setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets the zoom of the map. - */ - setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Increases the zoom of the map by delta (1 by default). - */ - zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Decreases the zoom of the map by delta (1 by default). - */ - zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Zooms the map while keeping a specified point on the map stationary - * (e.g. used internally for scroll zoom and double-click zoom). - */ - setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets a map view that contains the given geographical bounds with the maximum - * zoom level possible. - */ - fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; - - /** - * Sets a map view that mostly contains the whole world with the maximum zoom - * level possible. - */ - fitWorld(options?: Map.FitBoundsOptions): Map; - - /** - * Pans the map to a given center. Makes an animated pan if new center is not more - * than one screen away from the current one. - */ - panTo(latlng: LatLngExpression, options?: PanOptions): Map; - - /** - * Pans the map to the closest view that would lie inside the given bounds (if - * it's not already). - */ - panInsideBounds(bounds: LatLngBounds): Map; - - /** - * Pans the map by a given number of pixels (animated). - */ - panBy(point: Point, options?: PanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - * If options.pan is false, panning will not occur. - */ - invalidateSize(options: Map.ZoomPanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - */ - invalidateSize(animate: boolean): Map; - - /** - * Restricts the map view to the given bounds (see map maxBounds option), - * passing the given animation options through to `setView`, if required. - */ - setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; - - /** - * Tries to locate the user using Geolocation API, firing locationfound event - * with location data on success or locationerror event on failure, and optionally - * sets the map view to the user location with respect to detection accuracy - * (or to the world view if geolocation failed). See Locate options for more - * details. - */ - locate(options?: LocateOptions): Map; - - /** - * Stops watching location previously initiated by map.locate({watch: true}) - * and aborts resetting the map view if map.locate was called with {setView: true}. - */ - stopLocate(): Map; - - /** - * Destroys the map and clears all related event listeners. - */ - remove(): Map; - - // Methods for Getting Map State - - /** - * Returns the geographical center of the map view. - */ - getCenter(): LatLng; - - /** - * Returns the current zoom of the map view. - */ - getZoom(): number; - - /** - * Returns the minimum zoom level of the map. - */ - getMinZoom(): number; - - /** - * Returns the maximum zoom level of the map. - */ - getMaxZoom(): number; - - /** - * Returns the LatLngBounds of the current map view. - */ - getBounds(): LatLngBounds; - - /** - * Returns the maximum zoom level on which the given bounds fit to the map view - * in its entirety. If inside (optional) is set to true, the method instead returns - * the minimum zoom level on which the map view fits into the given bounds in its - * entirety. - */ - getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; - - /** - * Returns the current size of the map container. - */ - getSize(): Point; - - /** - * Returns the bounds of the current map view in projected pixel coordinates - * (sometimes useful in layer and overlay implementations). - */ - getPixelBounds(): Bounds; - - /** - * Returns the projected pixel coordinates of the top left point of the map layer - * (useful in custom layer and overlay implementations). - */ - getPixelOrigin(): Point; - - // Methods for Layers and Controls - - /** - * Adds the given layer to the map. If optional insertAtTheBottom is set to true, - * the layer is inserted under all others (useful when switching base tile layers). - */ - addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; - - /** - * Removes the given layer from the map. - */ - removeLayer(layer: ILayer): Map; - - /** - * Returns true if the given layer is currently added to the map. - */ - hasLayer(layer: ILayer): boolean; - - /** - * Opens the specified popup while closing the previously opened (to make sure - * only one is opened at one time for usability). - */ - openPopup(popup: Popup): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Closes the popup previously opened with openPopup (or the given one). - */ - closePopup(popup?: Popup): Map; - - /** - * Adds the given control to the map. - */ - addControl(control: IControl): Map; - - /** - * Removes the given control from the map. - */ - removeControl(control: IControl): Map; - - // Conversion Methods - - /** - * Returns the map layer point that corresponds to the given geographical coordinates - * (useful for placing overlays on the map). - */ - latLngToLayerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map layer point. - */ - layerPointToLatLng(point: Point): LatLng; - - /** - * Converts the point relative to the map container to a point relative to the - * map layer. - */ - containerPointToLayerPoint(point: Point): Point; - - /** - * Converts the point relative to the map layer to a point relative to the map - * container. - */ - layerPointToContainerPoint(point: Point): Point; - - /** - * Returns the map container point that corresponds to the given geographical - * coordinates. - */ - latLngToContainerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map container point. - */ - containerPointToLatLng(point: Point): LatLng; - - /** - * Projects the given geographical coordinates to absolute pixel coordinates - * for the given zoom level (current zoom level by default). - */ - project(latlng: LatLngExpression, zoom?: number): Point; - - /** - * Projects the given absolute pixel coordinates to geographical coordinates - * for the given zoom level (current zoom level by default). - */ - unproject(point: Point, zoom?: number): LatLng; - - /** - * Returns the pixel coordinates of a mouse click (relative to the top left corner - * of the map) given its event object. - */ - mouseEventToContainerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the pixel coordinates of a mouse click relative to the map layer given - * its event object. - */ - mouseEventToLayerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the geographical coordinates of the point the mouse clicked on given - * the click's event object. - */ - mouseEventToLatLng(event: LeafletMouseEvent): LatLng; - - // Other Methods - - /** - * Returns the container element of the map. - */ - getContainer(): HTMLElement; - - /** - * Returns an object with different map panes (to render overlays in). - */ - getPanes(): MapPanes; - - // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? - /** - * Runs the given callback when the map gets initialized with a place and zoom, - * or immediately if it happened already, optionally passing a function context. - */ - whenReady(fn: (map: Map) => void, context?: any): Map; - - // Properties - - /** - * Map dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - /** - * Touch zoom handler. - */ - touchZoom: IHandler; - - /** - * Double click zoom handler. - */ - doubleClickZoom: IHandler; - - /** - * Scroll wheel zoom handler. - */ - scrollWheelZoom: IHandler; - - /** - * Box (shift-drag with mouse) zoom handler. - */ - boxZoom: IHandler; - - /** - * Keyboard navigation handler. - */ - keyboard: IHandler; - - /** - * Mobile touch hacks (quick tap and touch hold) handler. - */ - tap: IHandler; - - /** - * Zoom control. - */ - zoomControl: Control.Zoom; - - /** - * Attribution control. - */ - attributionControl: Control.Attribution; - - /** - * Map state options - */ - options: Map.MapOptions; - - /** - * Iterates over the layers of the map, optionally specifying context - * of the iterator function. - */ - eachLayer(fn: (layer: ILayer) => void, context?: any): Map; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Map; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; - removeEventListener(eventMap?: any, context?: any): Map; - clearAllEventListeners(): Map; - on(eventMap: any, context?: any): Map; - off(eventMap?: any, context?: any): Map; - } -} - -declare namespace L.Map { - - export interface MapOptions { - - // Map State Options - - /** - * Initial geographical center of the map. - */ - center?: LatLng; - - /** - * Initial map zoom. - */ - zoom?: number; - - /** - * Layers that will be added to the map initially. - */ - layers?: ILayer[]; - - /** - * Minimum zoom level of the map. Overrides any minZoom set on map layers. - */ - minZoom?: number; - - /** - * Maximum zoom level of the map. This overrides any maxZoom set on map layers. - */ - maxZoom?: number; - - /** - * When this option is set, the map restricts the view to the given geographical - * bounds, bouncing the user back when he tries to pan outside the view, and also - * not allowing to zoom out to a view that's larger than the given bounds (depending - * on the map size). To set the restriction dynamically, use setMaxBounds method - */ - maxBounds?: LatLngBounds; - - /** - * Coordinate Reference System to use. Don't change this if you're not sure - * what it means. - * - * Default value: L.CRS.EPSG3857. - */ - crs?: ICRS; - - // Interaction Options - - /** - * Whether the map be draggable with mouse/touch or not. - * - * Default value: true. - */ - dragging?: boolean; - - /** - * Whether the map can be zoomed by touch-dragging with two fingers. - * - * Default value: true. - */ - touchZoom?: boolean; - - /** - * Whether the map can be zoomed by using the mouse wheel. - * If passed 'center', it will zoom to the center of the view regardless of - * where the mouse was. - * - * Default value: true. - */ - scrollWheelZoom?: boolean; - - /** - * Whether the map can be zoomed in by double clicking on it and zoomed out - * by double clicking while holding shift. - * If passed 'center', double-click zoom will zoom to the center of the view - * regardless of where the mouse was. - * - * Default value: true. - */ - doubleClickZoom?: boolean; - - /** - * Whether the map can be zoomed to a rectangular area specified by dragging - * the mouse while pressing shift. - * - * Default value: true. - */ - boxZoom?: boolean; - - /** - * Enables mobile hacks for supporting instant taps (fixing 200ms click delay - * on iOS/Android) and touch holds (fired as contextmenu events). - * - * Default value: true. - */ - tap?: boolean; - - /** - * The max number of pixels a user can shift his finger during touch for it - * to be considered a valid tap. - * - * Default value: 15. - */ - tapTolerance?: number; - - /** - * Whether the map automatically handles browser window resize to update itself. - * - * Default value: true. - */ - trackResize?: boolean; - - /** - * With this option enabled, the map tracks when you pan to another "copy" of - * the world and seamlessly jumps to the original one so that all overlays like - * markers and vector layers are still visible. - * - * Default value: false. - */ - worldCopyJump?: boolean; - - /** - * Set it to false if you don't want popups to close when user clicks the map. - * - * Default value: true. - */ - closePopupOnClick?: boolean; - - // Keyboard Navigation Options - - /** - * Makes the map focusable and allows users to navigate the map with keyboard - * arrows and +/- keys. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Amount of pixels to pan when pressing an arrow key. - * - * Default value: 80. - */ - keyboardPanOffset?: number; - - /** - * Number of zoom levels to change when pressing + or - key. - * - * Default value: 1. - */ - keyboardZoomOffset?: number; - - // Panning Inertia Options - - /** - * If enabled, panning of the map will have an inertia effect where the map builds - * momentum while dragging and continues moving in the same direction for some - * time. Feels especially nice on touch devices. - * - * Default value: true. - */ - inertia?: boolean; - - /** - * The rate with which the inertial movement slows down, in pixels/second2. - * - * Default value: 3000. - */ - inertiaDeceleration?: number; - - /** - * Max speed of the inertial movement, in pixels/second. - * - * Default value: 1500. - */ - inertiaMaxSpeed?: number; - - /** - * Amount of milliseconds that should pass between stopping the movement and - * releasing the mouse or touch to prevent inertial movement. - * - * Default value: 32 for touch devices and 14 for the rest. - */ - inertiaThreshold?: number; - - // Control options - - /** - * Whether the zoom control is added to the map by default. - * - * Default value: true. - */ - zoomControl?: boolean; - - /** - * Whether the attribution control is added to the map by default. - * - * Default value: true. - */ - attributionControl?: boolean; - - // Animation options - - /** - * Whether the tile fade animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ - fadeAnimation?: boolean; - - /** - * Whether the tile zoom animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ - zoomAnimation?: boolean; - - /** - * Won't animate zoom if the zoom difference exceeds this value. - * - * Default value: 4. - */ - zoomAnimationThreshold?: number; - - /** - * Whether markers animate their zoom with the zoom animation, if disabled - * they will disappear for the length of the animation. By default it's enabled - * in all browsers that support CSS3 Transitions except Android. - */ - markerZoomAnimation?: boolean; - - /** - * Set it to false if you don't want the map to zoom beyond min/max zoom - * and then bounce back when pinch-zooming. - * - * Default value: true. - */ - bounceAtZoomLimits?: boolean; - } - - export interface ZoomOptions { - /** - * If not specified, zoom animation will happen if the zoom origin is inside the current view. - * If true, the map will attempt animating zoom disregarding where zoom origin is. - * Setting false will make it always reset the view completely without animation. - */ - animate?: boolean; - } - - export interface ZoomPanOptions { - - /** - * If true, the map view will be completely reset (without any animations). - * - * Default value: false. - */ - reset?: boolean; - - /** - * Sets the options for the panning (without the zoom change) if it occurs. - */ - pan?: PanOptions; - - /** - * Sets the options for the zoom change if it occurs. - */ - zoom?: ZoomOptions; - - /** - * An equivalent of passing animate to both zoom and pan options (see below). - */ - animate?: boolean; - - /** - * If true, it will delay moveend event so that it doesn't happen many times in a row. - */ - debounceMoveend?: boolean; - } - - export interface FitBoundsOptions extends ZoomPanOptions { - - /** - * Sets the amount of padding in the top left corner of a map container that - * shouldn't be accounted for when setting the view to fit bounds. Useful if - * you have some control overlays on the map like a sidebar and you don't - * want them to obscure objects you're zooming to. - * - * Default value: [0, 0]. - */ - paddingTopLeft?: Point; - - /** - * The same for bottom right corner of the map. - * - * Default value: [0, 0]. - */ - paddingBottomRight?: Point; - - /** - * Equivalent of setting both top left and bottom right padding to the same value. - * - * Default value: [0, 0]. - */ - padding?: Point; - - /** - * The maximum possible zoom to use. - * - * Default value: null - */ - maxZoom?: number; - } -} - -declare namespace L { - - export interface MapPanes { - - /** - * Pane that contains all other map panes. - */ - mapPane: HTMLElement; - - /** - * Pane for tile layers. - */ - tilePane: HTMLElement; - - /** - * Pane that contains all the panes except tile pane. - */ - objectsPane: HTMLElement; - - /** - * Pane for overlay shadows (e.g. marker shadows). - */ - shadowPane: HTMLElement; - - /** - * Pane for overlays like polylines and polygons. - */ - overlayPane: HTMLElement; - - /** - * Pane for marker icons. - */ - markerPane: HTMLElement; - - /** - * Pane for popups. - */ - popupPane: HTMLElement; - } -} - -declare namespace L { - - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; - - var Marker: { - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - new(latlng: LatLngExpression, options?: MarkerOptions): Marker; - }; - - export interface Marker extends ILayer, IEventPowered { - /** - * Adds the marker to the map. - */ - addTo(map: Map): Marker; - - /** - * Returns the current geographical position of the marker. - */ - getLatLng(): LatLng; - - /** - * Changes the marker position to the given point. - */ - setLatLng(latlng: LatLngExpression): Marker; - - /** - * Changes the marker icon. - */ - setIcon(icon: Icon): Marker; - - /** - * Changes the zIndex offset of the marker. - */ - setZIndexOffset(offset: number): Marker; - - /** - * Changes the opacity of the marker. - */ - setOpacity(opacity: number): Marker; - - /** - * Updates the marker position, useful if coordinates of its latLng object - * were changed directly. - */ - update(): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(html: string, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(popup: Popup, options?: PopupOptions): Marker; - - /** - * Unbinds the popup previously bound to the marker with bindPopup. - */ - unbindPopup(): Marker; - - /** - * Opens the popup previously bound by the bindPopup method. - */ - openPopup(): Marker; - - /** - * Returns the popup previously bound by the bindPopup method. - */ - getPopup(): Popup; - - /** - * Closes the bound popup of the marker if it's opened. - */ - closePopup(): Marker; - - /** - * Toggles the popup previously bound by the bindPopup method. - */ - togglePopup(): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(html: string, options?: PopupOptions): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). - */ - toGeoJSON(): any; - - /** - * Marker dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Marker; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - fire(type: string, data?: any): Marker; - addEventListener(eventMap: any, context?: any): Marker; - removeEventListener(eventMap?: any, context?: any): Marker; - clearAllEventListeners(): Marker; - on(eventMap: any, context?: any): Marker; - off(eventMap?: any, context?: any): Marker; - } -} - -declare namespace L { - - export interface MarkerOptions { - - /** - * Icon class to use for rendering the marker. See Icon documentation for details - * on how to customize the marker icon. - * - * Default value: new L.Icon.Default(). - */ - icon?: Icon; - - /** - * If false, the marker will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Whether the marker is draggable with mouse/touch or not. - * - * Default value: false. - */ - draggable?: boolean; - - /** - * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Text for the browser tooltip that appear on marker hover (no tooltip by default). - * - * Default value: ''. - */ - title?: string; - - /** - * Text for the alt attribute of the icon image (useful for accessibility). - * - * Default value: ''. - */ - alt?: string; - - /** - * By default, marker images zIndex is set automatically based on its latitude. - * You this option if you want to put the marker on top of all others (or below), - * specifying a high value like 1000 (or high negative value, respectively). - * - * Default value: 0. - */ - zIndexOffset?: number; - - /** - * The opacity of the marker. - * - * Default value: 1.0. - */ - opacity?: number; - - /** - * If true, the marker will get on top of others when you hover the mouse over it. - * - * Default value: false. - */ - riseOnHover?: boolean; - - /** - * The z-index offset used for the riseOnHover feature. - * - * Default value: 250. - */ - riseOffset?: number; - } -} - -declare namespace L { - - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; - - export interface MultiPolygonStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; - } - export var MultiPolygon: MultiPolygonStatic; - - export interface MultiPolygon extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolygon; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolygon; - - /** - * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). - */ - toGeoJSON(): any; - } -} - -declare namespace L { - - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - - export interface MultiPolylineStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - } - export var MultiPolyline: MultiPolylineStatic; - - export interface MultiPolyline extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolyline; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolyline; - - /** - * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). - */ - toGeoJSON(): any; - } -} - -declare namespace L { - - export interface PanOptions { - - /** - * If true, panning will always be animated if possible. If false, it will not - * animate panning, either resetting the map view if panning more than a screen - * away, or just setting a new offset for the map pane (except for `panBy` - * which always does the latter). - */ - animate?: boolean; - - /** - * Duration of animated panning. - * - * Default value: 0.25. - */ - duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic - * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. - * - * Default value: 0.25. - */ - easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - * - * Default value: false. - */ - noMoveStart?: boolean; - } -} - -declare namespace L { - - export interface Path extends ILayer, IEventPowered { - - /** - * Adds the layer to the map. - */ - addTo(map: Map): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(html: string, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(popup: Popup, options?: PopupOptions): Path; - - /** - * Unbinds the popup previously bound to the path with bindPopup. - */ - unbindPopup(): Path; - - /** - * Opens the popup previously bound by the bindPopup method in the given point, - * or in one of the path's points if not specified. - */ - openPopup(latlng?: LatLngExpression): Path; - - /** - * Closes the path's bound popup if it is opened. - */ - closePopup(): Path; - - /** - * Changes the appearance of a Path based on the options in the Path options object. - */ - setStyle(object: PathOptions): Path; - - /** - * Returns the LatLngBounds of the path. - */ - getBounds(): LatLngBounds; - - /** - * Brings the layer to the top of all path layers. - */ - bringToFront(): Path; - - /** - * Brings the layer to the bottom of all path layers. - */ - bringToBack(): Path; - - /** - * Redraws the layer. Sometimes useful after you changed the coordinates that - * the path uses. - */ - redraw(): Path; - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Path; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - fire(type: string, data?: any): Path; - addEventListener(eventMap: any, context?: any): Path; - removeEventListener(eventMap?: any, context?: any): Path; - clearAllEventListeners(): Path; - on(eventMap: any, context?: any): Path; - off(eventMap?: any, context?: any): Path; - } - - export namespace Path { - /** - * True if SVG is used for vector rendering (true for most modern browsers). - */ - export var SVG: boolean; - - /** - * True if VML is used for vector rendering (IE 6-8). - */ - export var VML: boolean; - - /** - * True if Canvas is used for vector rendering (Android 2). You can also force - * this by setting global variable L_PREFER_CANVAS to true before the Leaflet - * include on your page — sometimes it can increase performance dramatically - * when rendering thousands of circle markers, but currently suffers from - * a bug that causes removing such layers to be extremely slow. - */ - export var CANVAS: boolean; - - /** - * How much to extend the clip area around the map view (relative to its size, - * e.g. 0.5 is half the screen in each direction). Smaller values mean that you - * will see clipped ends of paths while you're dragging the map, and bigger values - * decrease drawing performance. - */ - export var CLIP_PADDING: number; - } -} - -declare namespace L { - - export interface PathOptions { - - /** - * Whether to draw stroke along the path. Set it to false to disable borders on - * polygons or circles. - * - * Default value: true. - */ - stroke?: boolean; - - /** - * Stroke color. - * - * Default value: '#03f'. - */ - color?: string; - - /** - * Stroke width in pixels. - * - * Default value: 5. - */ - weight?: number; - - /** - * Stroke opacity. - * - * Default value: 0.5. - */ - opacity?: number; - - /** - * Whether to fill the path with color. Set it to false to disable filling on polygons - * or circles. - */ - fill?: boolean; - - /** - * Fill color. - * - * Default value: same as color. - */ - fillColor?: string; - - /** - * Fill opacity. - * - * Default value: 0.2. - */ - fillOpacity?: number; - - /** - * A string that defines the stroke dash pattern. Doesn't work on canvas-powered - * layers (e.g. Android 2). - */ - dashArray?: string; - - /** - * A string that defines shape to be used at the end of the stroke. - * - * Default: null. - */ - lineCap?: string; - - /** - * A string that defines shape to be used at the corners of the stroke. - * - * Default: null. - */ - lineJoin?: string; - - /** - * If false, the vector will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Sets the pointer-events attribute on the path if SVG backend is used. - */ - pointerEvents?: string; - - /** - * Custom class name set on an element. - * - * Default value: ''. - */ - className?: string; - - } -} - -declare namespace L { - - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - function point(x: number, y: number, round?: boolean): Point; - - export interface PointStatic { - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - new(x: number, y: number, round?: boolean): Point; - } - export var Point: PointStatic; - - export interface Point { - /** - * Returns the result of addition of the current and the given points. - */ - add(otherPoint: Point): Point; - - /** - * Returns the result of subtraction of the given point from the current. - */ - subtract(otherPoint: Point): Point; - - /** - * Returns the result of multiplication of the current point by the given number. - */ - multiplyBy(number: number): Point; - - /** - * Returns the result of division of the current point by the given number. If - * optional round is set to true, returns a rounded result. - */ - divideBy(number: number, round?: boolean): Point; - - /** - * Returns the distance between the current and the given points. - */ - distanceTo(otherPoint: Point): number; - - /** - * Returns a copy of the current point. - */ - clone(): Point; - - /** - * Returns a copy of the current point with rounded coordinates. - */ - round(): Point; - - /** - * Returns true if the given point has the same coordinates. - */ - equals(otherPoint: Point): boolean; - - /** - * Returns a string representation of the point for debugging purposes. - */ - toString(): string; - - /** - * The x coordinate. - */ - x: number; - - /** - * The y coordinate. - */ - y: number; - } -} - -declare namespace L { - - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - - - export interface PolygonStatic extends ClassStatic { - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - } - export var Polygon: PolygonStatic; - - export interface Polygon extends Polyline { - } -} - -declare namespace L { - - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - - export interface PolylineStatic extends ClassStatic { - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - } - export var Polyline: PolylineStatic; - - export interface Polyline extends Path { - /** - * Adds a given point to the polyline. - */ - addLatLng(latlng: LatLngExpression): Polyline; - - /** - * Replaces all the points in the polyline with the given array of geographical - * points. - */ - setLatLngs(latlngs: LatLngBoundsExpression): Polyline; - - /** - * Returns an array of the points in the path. - */ - getLatLngs(): LatLng[]; - - /** - * Allows adding, removing or replacing points in the polyline. Syntax is the - * same as in Array#splice. Returns the array of removed points (if any). - */ - spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; - - /** - * Returns the LatLngBounds of the polyline. - */ - getBounds(): LatLngBounds; - - /** - * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). - */ - toGeoJSON(): any; - } -} - -declare namespace L { - - export interface PolylineOptions extends PathOptions { - - /** - * How much to simplify the polyline on each zoom level. More means better performance - * and smoother look, and less means more accurate representation. - * - * Default value: 1.0. - */ - smoothFactor?: number; - - /** - * Disabled polyline clipping. - * - * Default value: false. - */ - noClip?: boolean; - } -} - -declare namespace L { - - namespace PolyUtil { - - /** - * Clips the polygon geometry defined by the given points by rectangular bounds. - * Used by Leaflet to only show polygon points that are on the screen or near, - * increasing performance. Note that polygon points needs different algorithm - * for clipping than polyline, so there's a seperate method for it. - */ - export function clipPolygon(points: Point[], bounds: Bounds): Point[]; - } -} - -declare namespace L { - - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - function popup(options?: PopupOptions, source?: any): Popup; - - export interface PopupStatic extends ClassStatic { - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - new(options?: PopupOptions, source?: any): Popup; - } - export var Popup: PopupStatic; - - export interface Popup extends ILayer { - /** - * Adds the popup to the map. - */ - addTo(map: Map): Popup; - - /** - * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). - */ - openOn(map: Map): Popup; - - /** - * Sets the geographical point where the popup will open. - */ - setLatLng(latlng: LatLngExpression): Popup; - - /** - * Returns the geographical point of popup. - */ - getLatLng(): LatLng; - - /** - * Sets the HTML content of the popup. - */ - setContent(html: string): Popup; - - /** - * Sets the HTML content of the popup. - */ - setContent(el: HTMLElement): Popup; - - /** - * Returns the content of the popup. - */ - getContent(): HTMLElement; - //getContent(): string; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - /** - * Updates the popup content, layout and position. Useful for updating the popup after - * something inside changed, e.g. image loaded. - */ - update(): Popup; - } -} - -declare namespace L { - - export interface PopupOptions { - - /** - * Max width of the popup. - * - * Default value: 300. - */ - maxWidth?: number; - - /** - * Min width of the popup. - * - * Default value: 50. - */ - minWidth?: number; - - /** - * If set, creates a scrollable container of the given height inside a popup - * if its content exceeds it. - */ - maxHeight?: number; - - /** - * Set it to false if you don't want the map to do panning animation to fit the opened - * popup. - * - * Default value: true. - */ - autoPan?: boolean; - - /** - * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. - */ - keepInView?: boolean; - - /** - * Controls the presense of a close button in the popup. - * - * Default value: true. - */ - closeButton?: boolean; - - /** - * The offset of the popup position. Useful to control the anchor of the popup - * when opening it on some overlays. - * - * Default value: new Point(0, 6). - */ - offset?: Point; - - /** - * The margin between the popup and the top left corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingTopLeft?: Point; - - /** - * The margin between the popup and the bottom right corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingBottomRight?: Point; - - /** - * The margin between the popup and the edges of the map view after autopanning - * was performed. - * - * Default value: new Point(5, 5). - */ - autoPanPadding?: Point; - - /** - * Whether to animate the popup on zoom. Disable it if you have problems with - * Flash content inside popups. - * - * Default value: true. - */ - zoomAnimation?: boolean; - - /** - * Set it to false if you want to override the default behavior of the popup - * closing when user clicks the map (set globally by the Map closePopupOnClick - * option). - */ - closeOnClick?: boolean; - - /** - * A custom class name to assign to the popup. - */ - className?: string; - } -} - -declare namespace L { - - export interface PosAnimationStatic extends ClassStatic { - /** - * Creates a PosAnimation object. - */ - new(): PosAnimation; - } - export var PosAnimation: PosAnimationStatic; - - export interface PosAnimation extends IEventPowered { - /** - * Run an animation of a given element to a new position, optionally setting - * duration in seconds (0.25 by default) and easing linearity factor (3rd argument - * of the cubic bezier curve, 0.5 by default) - */ - run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): PosAnimation; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - fire(type: string, data?: any): PosAnimation; - addEventListener(eventMap: any, context?: any): PosAnimation; - removeEventListener(eventMap?: any, context?: any): PosAnimation; - clearAllEventListeners(): PosAnimation; - on(eventMap: any, context?: any): PosAnimation; - off(eventMap?: any, context?: any): PosAnimation; - } -} - -declare namespace L { - - namespace Projection { - - /** - * Spherical Mercator projection — the most common projection for online maps, - * used by almost all free and commercial tile providers. Assumes that Earth - * is a sphere. Used by the EPSG:3857 CRS. - */ - export var SphericalMercator: IProjection; - - /** - * Elliptical Mercator projection — more complex than Spherical Mercator. - * Takes into account that Earth is a geoid, not a perfect sphere. Used by the - * EPSG:3395 CRS. - */ - export var Mercator: IProjection; - - /** - * Equirectangular, or Plate Carree projection — the most simple projection, - * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. - * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple - * CRS. - */ - export var LonLat: IProjection; - } -} - -declare namespace L { - - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; - - export interface RectangleStatic extends ClassStatic { - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - new(bounds: LatLngBounds, options?: PathOptions): Rectangle; - } - export var Rectangle: RectangleStatic; - - export interface Rectangle extends Polygon { - /** - * Redraws the rectangle with the passed bounds. - */ - setBounds(bounds: LatLngBounds): Rectangle; - } -} - - -declare namespace L { - - export interface ScaleOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomleft'. - */ - position?: string; - - /** - * Maximum width of the control in pixels. The width is set dynamically to show - * round values (e.g. 100, 200, 500). - * Default value: 100. - */ - maxWidth?: number; - - /** - * Whether to show the metric scale line (m/km). - * Default value: true. - */ - metric?: boolean; - - /** - * Whether to show the imperial scale line (mi/ft). - * Default value: true. - */ - imperial?: boolean; - - /** - * If true, the control is updated on moveend, otherwise it's always up-to-date - * (updated on move). - * Default value: false. - */ - updateWhenIdle?: boolean; - } -} - -declare namespace L { - - export interface TileLayerStatic extends ClassStatic { - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - new(urlTemplate: string, options?: TileLayerOptions): TileLayer; - - WMS: { - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - new(baseUrl: string, options: WMSOptions): TileLayer.WMS; - }; - - Canvas: { - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - new(options?: TileLayerOptions): TileLayer.Canvas; - }; - } - export var TileLayer: TileLayerStatic; - - export interface TileLayer extends ILayer, IEventPowered { - /** - * Adds the layer to the map. - */ - addTo(map: Map): TileLayer; - - /** - * Brings the tile layer to the top of all tile layers. - */ - bringToFront(): TileLayer; - - /** - * Brings the tile layer to the bottom of all tile layers. - */ - bringToBack(): TileLayer; - - /** - * Changes the opacity of the tile layer. - */ - setOpacity(opacity: number): TileLayer; - - /** - * Sets the zIndex of the tile layer. - */ - setZIndex(zIndex: number): TileLayer; - - /** - * Causes the layer to clear all the tiles and request them again. - */ - redraw(): TileLayer; - - /** - * Updates the layer's URL template and redraws it. - */ - setUrl(urlTemplate: string): TileLayer; - - /** - * Returns the HTML element that contains the tiles for this layer. - */ - getContainer(): HTMLElement; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): TileLayer; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - fire(type: string, data?: any): TileLayer; - addEventListener(eventMap: any, context?: any): TileLayer; - removeEventListener(eventMap?: any, context?: any): TileLayer; - clearAllEventListeners(): TileLayer; - on(eventMap: any, context?: any): TileLayer; - off(eventMap?: any, context?: any): TileLayer; - } - - namespace TileLayer { - export interface WMS extends TileLayer { - /** - * Merges an object with the new parameters and re-requests tiles on the current - * screen (unless noRedraw was set to true). - */ - setParams(params: WMS, noRedraw?: boolean): WMS; - } - - export interface Canvas extends TileLayer { - /** - * You need to define this method after creating the instance to draw tiles; - * canvas is the actual canvas tile on which you can draw, tilePoint represents - * the tile numbers, and zoom is the current zoom. - */ - drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; - - /** - * Calling redraw will cause the drawTile method to be called for all tiles. - * May be used for updating dynamic content drawn on the Canvas - */ - redraw(): Canvas; - } - } - - export interface TileLayerFactory { - - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - (urlTemplate: string, options?: TileLayerOptions): TileLayer; - - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; - - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - canvas(options?: TileLayerOptions): L.TileLayer.Canvas; - } - - export var tileLayer: TileLayerFactory; -} - -declare namespace L { - - export interface TileLayerOptions { - - /** - * Minimum zoom number. - * - * Default value: 0. - */ - minZoom?: number; - - /** - * Maximum zoom number. - * - * Default value: 18. - */ - maxZoom?: number; - - /** - * Maximum zoom number the tiles source has available. If it is specified, - * the tiles on all zoom levels higher than maxNativeZoom will be loaded from - * maxZoom level and auto-scaled. - * - * Default value: null. - */ - maxNativeZoom?: number; - - /** - * Tile size (width and height in pixels, assuming tiles are square). - * - * Default value: 256. - */ - tileSize?: number; - - /** - * Subdomains of the tile service. Can be passed in the form of one string (where - * each letter is a subdomain name) or an array of strings. - * - * Default value: 'abc'. - */ - subdomains?: string[]; - - /** - * URL to the tile image to show in place of the tile that failed to load. - * - * Default value: ''. - */ - errorTileUrl?: string; - - /** - * e.g. "© CloudMade" — the string used by the attribution control, describes - * the layer data. - * - * Default value: ''. - */ - attribution?: string; - - /** - * If true, inverses Y axis numbering for tiles (turn this on for TMS services). - * - * Default value: false. - */ - tms?: boolean; - - /** - * If set to true, the tile coordinates won't be wrapped by world width (-180 - * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this - * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor - * or photo maps). - * - * Default value: false. - */ - continuousWorld?: boolean; - - /** - * If set to true, the tiles just won't load outside the world width (-180 to 180 - * longitude) instead of repeating. - * - * Default value: false. - */ - noWrap?: boolean; - - /** - * The zoom number used in tile URLs will be offset with this value. - * - * Default value: 0. - */ - zoomOffset?: number; - - /** - * If set to true, the zoom number used in tile URLs will be reversed (maxZoom - * - zoom instead of zoom) - * - * Default value: false. - */ - zoomReverse?: boolean; - - /** - * The opacity of the tile layer. - * - * Default value: 1.0. - */ - opacity?: number; - - /** - * The explicit zIndex of the tile layer. Not set by default. - */ - zIndex?: number; - - /** - * If true, all the tiles that are not visible after panning are removed (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - unloadInvisibleTiles?: boolean; - - /** - * If false, new tiles are loaded during panning, otherwise only after it (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - updateWhenIdle?: boolean; - - /** - * If true and user is on a retina display, it will request four tiles of half the - * specified size and a bigger zoom level in place of one to utilize the high resolution. - * - * Default value: false. - */ - detectRetina?: boolean; - - /** - * If true, all the tiles that are not visible after panning are placed in a reuse - * queue from which they will be fetched when new tiles become visible (as opposed - * to dynamically creating new ones). This will in theory keep memory usage - * low and eliminate the need for reserving new memory whenever a new tile is - * needed. - * - * Default value: false. - */ - reuseTiles?: boolean; - - /** - * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. - */ - bounds?: LatLngBounds; - - /** - * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. - */ - [additionalKeys: string]: any; - } -} - -declare namespace L { - export interface TransformationStatic { - /** - * Creates a transformation object with the given coefficients. - */ - new(a: number, b: number, c: number, d: number): Transformation; - } - export var Transformation: TransformationStatic; - - export interface Transformation { - /** - * Returns a transformed point, optionally multiplied by the given scale. - * Only accepts real L.Point instances, not arrays. - */ - transform(point: Point, scale?: number): Point; - - /** - * Returns the reverse transformation of the given point, optionally divided - * by the given scale. Only accepts real L.Point instances, not arrays. - */ - untransform(point: Point, scale?: number): Point; - } -} - -declare namespace L { - - namespace Util { - - /** - * Merges the properties of the src object (or multiple objects) into dest object - * and returns the latter. Has an L.extend shortcut. - */ - export function extend(dest: any, ...sources: any[]): any; - - /** - * Returns a function which executes function fn with the given scope obj (so - * that this keyword refers to obj inside the function code). Has an L.bind shortcut. - */ - export function bind(fn: T, obj: any): T; - - /** - * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. - */ - export function stamp(obj: any): string; - - /** - * Returns a wrapper around the function fn that makes sure it's called not more - * often than a certain time interval time, but as fast as possible otherwise - * (for example, it is used for checking and requesting new tiles while dragging - * the map), optionally passing the scope (context) in which the function will - * be called. - */ - export function limitExecByInterval(fn: T, time: number, context?: any): T; - - /** - * Returns a function which always returns false. - */ - export function falseFn(): () => boolean; - - /** - * Returns the number num rounded to digits decimals. - */ - export function formatNum(num: number, digits: number): number; - - /** - * Trims and splits the string on whitespace and returns the array of parts. - */ - export function splitWords(str: string): string[]; - - /** - * Merges the given properties to the options of the obj object, returning the - * resulting options. See Class options. Has an L.setOptions shortcut. - */ - export function setOptions(obj: any, options: any): any; - - /** - * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} - * translates to '?a=foo&b=bar'. - */ - export function getParamString(obj: any): string; - - /** - * Simple templating facility, creates a string by applying the values of the - * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form - * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. - */ - export function template(str: string, data: any): string; - - /** - * Returns true if the given object is an array. - */ - export function isArray(obj: any): boolean; - - /** - * Trims the whitespace from both ends of the string and returns the result. - */ - export function trim(str: string): string; - - /** - * Data URI string containing a base64-encoded empty GIF image. Used as a hack - * to free memory from unused images on WebKit-powered mobile devices (by setting - * image src to this string). - */ - export var emptyImageUrl: string; - } -} - - -declare namespace L { - - export interface WMSOptions { - - /** - * (required) Comma-separated list of WMS layers to show. - * - * Default value: ''. - */ - layers?: string; - - /** - * Comma-separated list of WMS styles. - * - * Default value: 'image/jpeg'. - */ - styles?: string; - - /** - * WMS image format (use 'image/png' for layers with transparency). - * - * Default value: false. - */ - format?: string; - - /** - * If true, the WMS service will return images with transparency. - * - * Default value: '1.1.1'. - */ - transparent?: boolean; - - /** - * Version of the WMS service to use. - */ - version?: string; - - } -} - -/** - * Forces Leaflet to use the Canvas back-end (if available) for vector layers - * instead of SVG. This can increase performance considerably in some cases - * (e.g. many thousands of circle markers on the map). - */ -declare var L_PREFER_CANVAS: boolean; - -/** - * Forces Leaflet to not use touch events even if it detects them. - */ -declare var L_NO_TOUCH: boolean; - -/** - * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning - * (which may cause glitches in some rare environments) even if they're supported. - */ -declare var L_DISABLE_3D: boolean; - -declare module "leaflet" { - export = L; -} - -// vim: et ts=4 sw=4 +// Type definitions for Leaflet.js 0.7.3 +// Project: https://github.com/Leaflet/Leaflet +// Definitions by: Vladimir Zotov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module L { + type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) + type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; +} + +declare module L { + + export interface AttributionOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomright'. + */ + position?: string; + + /** + * The HTML text shown before the attributions. Pass false to disable. + * Default value: 'Powered by Leaflet'. + */ + prefix?: string; + + } +} + +declare module L { + + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + export function bounds(points: Point[]): Bounds; + + + export interface BoundsStatic { + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + new(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + new(points: Point[]): Bounds; + } + export var Bounds: BoundsStatic; + + export interface Bounds { + /** + * Extends the bounds to contain the given point. + */ + extend(point: Point): void; + + /** + * Returns the center point of the bounds. + */ + getCenter(): Point; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: Bounds): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(point: Point): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: Bounds): boolean; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + /** + * Returns the size of the given bounds. + */ + getSize(): Point; + + /** + * The top left corner of the rectangle. + */ + min: Point; + + /** + * The bottom right corner of the rectangle. + */ + max: Point; + } +} + +declare module L { + + module Browser { + + /** + * true for all Internet Explorer versions. + */ + export var ie: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie6: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie7: boolean; + + /** + * true for webkit-based browsers like Chrome and Safari (including mobile + * versions). + */ + export var webkit: boolean; + + /** + * true for webkit-based browsers that support CSS 3D transformations. + */ + export var webkit3d: boolean; + + /** + * true for Android mobile browser. + */ + export var android: boolean; + + /** + * true for old Android stock browsers (2 and 3). + */ + export var android23: boolean; + + /** + * true for modern mobile browsers (including iOS Safari and different Android + * browsers). + */ + export var mobile: boolean; + + /** + * true for mobile webkit-based browsers. + */ + export var mobileWebkit: boolean; + + /** + * true for mobile Opera. + */ + export var mobileOpera: boolean; + + /** + * true for all browsers on touch devices. + */ + export var touch: boolean; + + /** + * true for browsers with Microsoft touch model (e.g. IE10). + */ + export var msTouch: boolean; + + /** + * true for devices with Retina screens. + */ + export var retina: boolean; + + } +} + + +declare module L { + + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + + export interface CircleStatic extends ClassStatic { + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + } + export var Circle: CircleStatic; + + export interface Circle extends Path { + /** + * Returns the current geographical position of the circle. + */ + getLatLng(): LatLng; + + /** + * Returns the current radius of a circle. Units are in meters. + */ + getRadius(): number; + + /** + * Sets the position of a circle to a new location. + */ + setLatLng(latlng: LatLngExpression): Circle; + + /** + * Sets the radius of a circle. Units are in meters. + */ + setRadius(radius: number): Circle; + + /** + * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). + */ + toGeoJSON(): any; + + } +} + +declare module L { + + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + + + export interface CircleMarkerStatic extends ClassStatic { + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + } + export var CircleMarker: CircleMarkerStatic; + + export interface CircleMarker extends Circle { + /** + * Sets the position of a circle marker to a new location. + */ + setLatLng(latlng: LatLngExpression): CircleMarker; + + /** + * Sets the radius of a circle marker. Units are in pixels. + */ + setRadius(radius: number): CircleMarker; + + /** + * Returns a GeoJSON representation of the circle marker (GeoJSON Point Feature). + */ + toGeoJSON(): any; + } +} + +declare module L { + export interface ClassExtendOptions { + /** + * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. + */ + initialize?: Function; + + /** + * options is a special property that unlike other objects that you pass + * to extend will be merged with the parent one instead of overriding it + * completely, which makes managing configuration of objects and default + * values convenient. + */ + options?: any; + + /** + * includes is a special class property that merges all specified objects + * into the class (such objects are called mixins). A good example of this + * is L.Mixin.Events that event-related methods like on, off and fire + * to the class. + */ + includes?: any; + + /** + * statics is just a convenience property that injects specified object + * properties as the static properties of the class, useful for defining + * constants. + */ + static?: any; + + [prop: string]: any; + } + + export interface ClassStatic { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + extend(options: ClassExtendOptions): any; + extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; + + /** + * You can also use the following shortcut when you just need to make + * one additional method call. + */ + addInitHook(methodName: string, ...args: any[]): void; + } + + + /** + * L.Class powers the OOP facilities of Leaflet and is used to create + * almost all of the Leaflet classes documented. + */ + module Class { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + function extend(options: ClassExtendOptions): any; + } + +} + +declare module L { + export interface ControlStatic extends ClassStatic { + /** + * Creates a control with the given options. + */ + new(options?: ControlOptions): Control; + + Zoom: Control.ZoomStatic; + Attribution: Control.AttributionStatic; + Layers: Control.LayersStatic; + Scale: Control.ScaleStatic; + } + export var Control: ControlStatic; + + export interface Control extends IControl { + /** + * Sets the position of the control. See control positions. + */ + setPosition(position: string): Control; + + /** + * Returns the current position of the control. + */ + getPosition(): string; + + /** + * Adds the control to the map. + */ + addTo(map: Map): Control; + + /** + * Removes the control from the map. + */ + removeFrom(map: Map): Control; + + /** + * Returns the HTML container of the control. + */ + getContainer(): HTMLElement; + + // IControl members + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } + + namespace Control { + export interface ZoomStatic extends ClassStatic { + /** + * Creates a zoom control. + */ + new (options?: ZoomOptions): Zoom; + } + + export interface Zoom extends L.Control { + } + + export interface ZoomOptions { + /** + * The position of the control (one of the map corners). + * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. + * + * Default value: 'topright'. + */ + position?: string; // 'topleft' | 'topright' | 'bottomleft' | 'bottomright' + + /** + * The text set on the zoom in button. + * + * Default value: '+' + */ + zoomInText?: string; + + /** + * The text set on the zoom out button. + * + * Default value: '-' + */ + zoomOutText?: string; + + /** + * The title set on the zoom in button. + * + * Default value: 'Zoom in' + */ + zoomInTitle?: string; + + /** + * The title set on the zoom out button. + * + * Default value: 'Zoom out' + */ + zoomOutTitle?: string; + } + + export interface AttributionStatic extends ClassStatic { + /** + * Creates an attribution control. + */ + new(options?: AttributionOptions): Attribution; + } + + export interface Attribution extends L.Control { + /** + * Sets the text before the attributions. + */ + setPrefix(prefix: string): Attribution; + + /** + * Adds an attribution text (e.g. 'Vector data © CloudMade'). + */ + addAttribution(text: string): Attribution; + + /** + * Removes an attribution text. + */ + removeAttribution(text: string): Attribution; + + } + + export interface LayersStatic extends ClassStatic { + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; + } + + export interface Layers extends L.Control, IEventPowered { + /** + * Adds a base layer (radio button entry) with the given name to the control. + */ + addBaseLayer(layer: ILayer, name: string): Layers; + + /** + * Adds an overlay (checkbox entry) with the given name to the control. + */ + addOverlay(layer: ILayer, name: string): Layers; + + /** + * Remove the given layer from the control. + */ + removeLayer(layer: ILayer): Layers; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Layers; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + fire(type: string, data?: any): Layers; + addEventListener(eventMap: any, context?: any): Layers; + removeEventListener(eventMap?: any, context?: any): Layers; + clearAllEventListeners(): Layers; + on(eventMap: any, context?: any): Layers; + off(eventMap?: any, context?: any): Layers; + } + + export interface ScaleStatic extends ClassStatic { + /** + * Creates an scale control with the given options. + */ + new(options?: ScaleOptions): Scale; + } + + export interface Scale extends L.Control { + } + } + + export interface control { + /** + * Creates a control with the given options. + */ + (options?: ControlOptions): Control; + } + + export namespace control { + + /** + * Creates a zoom control. + */ + export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; + + /** + * Creates an attribution control. + */ + export function attribution(options?: AttributionOptions): L.Control.Attribution; + + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; + + /** + * Creates an scale control with the given options. + */ + export function scale(options?: ScaleOptions): L.Control.Scale; + } +} + +declare namespace L { + + export interface ControlOptions { + + /** + * The initial position of the control (one of the map corners). See control + * positions. + * Default value: 'topright'. + */ + position?: string; + + } +} + +declare namespace L { + + namespace CRS { + + /** + * The most common CRS for online maps, used by almost all free and commercial + * tile providers. Uses Spherical Mercator projection. Set in by default in + * Map's crs option. + */ + export var EPSG3857: ICRS; + + /** + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. + */ + export var EPSG4326: ICRS; + + /** + * Rarely used by some commercial tile providers. Uses Elliptical Mercator + * projection. + */ + export var EPSG3395: ICRS; + + /** + * A simple CRS that maps longitude and latitude into x and y directly. May be + * used for maps of flat surfaces (e.g. game maps). Note that the y axis should + * still be inverted (going from bottom to top). + */ + export var Simple: ICRS; + + } +} + +declare namespace L { + + /** + * Creates a div icon instance with the given options. + */ + function divIcon(options: DivIconOptions): DivIcon; + + export interface DivIconStatic extends ClassStatic { + /** + * Creates a div icon instance with the given options. + */ + new(options: DivIconOptions): DivIcon; + } + export var DivIcon: DivIconStatic; + + export interface DivIcon extends Icon { + } +} + +declare namespace L { + + export interface DivIconOptions { + + /** + * Size of the icon in pixels. Can be also set through CSS. + */ + iconSize?: Point; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point; + + /** + * A custom class name to assign to the icon. + * + * Default value: 'leaflet-div-icon'. + */ + className?: string; + + /** + * A custom HTML code to put inside the div element. + * + * Default value: ''. + */ + html?: string; + + } +} + +declare namespace L { + + export interface DomEvent { + + /** + * Adds a listener fn to the element's DOM event of the specified type. this keyword + * inside the listener will point to context, or to the element if not specified. + */ + addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Removes an event listener from the element. + */ + removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Stop the given event from propagation to parent elements. Used inside the + * listener functions: + * L.DomEvent.addListener(div, 'click', function + * (e) { + * L.DomEvent.stopPropagation(e); + * }); + */ + stopPropagation(e: Event): DomEvent; + + /** + * Prevents the default action of the event from happening (such as following + * a link in the href of the a element, or doing a POST request with page reload + * when form is submitted). Use it inside listener functions. + */ + preventDefault(e: Event): DomEvent; + + /** + * Does stopPropagation and preventDefault at the same time. + */ + stop(e: Event): DomEvent; + + /** + * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' + * and 'touchstart' events. + */ + disableClickPropagation(el: HTMLElement): DomEvent; + + /** + * Gets normalized mouse position from a DOM event relative to the container + * or to the whole page if not specified. + */ + getMousePosition(e: Event, container?: HTMLElement): Point; + + /** + * Gets normalized wheel delta from a mousewheel DOM event. + */ + getWheelDelta(e: Event): number; + + } + + export var DomEvent: DomEvent; +} + +declare namespace L { + + namespace DomUtil { + + /** + * Returns an element with the given id if a string was passed, or just returns + * the element if it was passed directly. + */ + export function get(id: string): HTMLElement; + + /** + * Returns the value for a certain style attribute on an element, including + * computed values or values set through CSS. + */ + export function getStyle(el: HTMLElement, style: string): string; + + /** + * Returns the offset to the viewport for the requested element. + */ + export function getViewportOffset(el: HTMLElement): Point; + + /** + * Creates an element with tagName, sets the className, and optionally appends + * it to container element. + */ + export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; + + /** + * Makes sure text cannot be selected, for example during dragging. + */ + export function disableTextSelection(): void; + + /** + * Makes text selection possible again. + */ + export function enableTextSelection(): void; + + /** + * Returns true if the element class attribute contains name. + */ + export function hasClass(el: HTMLElement, name: string): boolean; + + /** + * Adds name to the element's class attribute. + */ + export function addClass(el: HTMLElement, name: string): void; + + /** + * Removes name from the element's class attribute. + */ + export function removeClass(el: HTMLElement, name: string): void; + + /** + * Set the opacity of an element (including old IE support). Value must be from + * 0 to 1. + */ + export function setOpacity(el: HTMLElement, value: number): void; + + /** + * Goes through the array of style names and returns the first name that is a valid + * style name for an element. If no such name is found, it returns false. Useful + * for vendor-prefixed styles like transform. + */ + export function testProp(props: string[]): any; + + /** + * Returns a CSS transform string to move an element by the offset provided in + * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms + * and 2D on other browsers. + */ + export function getTranslateString(point: Point): string; + + /** + * Returns a CSS transform string to scale an element (with the given scale origin). + */ + export function getScaleString(scale: number, origin: Point): string; + + /** + * Sets the position of an element to coordinates specified by point, using + * CSS translate or top/left positioning depending on the browser (used by + * Leaflet internally to position its layers). Forces top/left positioning + * if disable3D is true. + */ + export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; + + /** + * Returns the coordinates of an element previously positioned with setPosition. + */ + export function getPosition(el: HTMLElement): Point; + + /** + * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). + */ + export var TRANSITION: string; + + /** + * Vendor-prefixed transform style name. + */ + export var TRANSFORM: string; + + } +} + +declare namespace L { + export interface DraggableStatic extends ClassStatic { + /** + * Creates a Draggable object for moving the given element when you start dragging + * the dragHandle element (equals the element itself by default). + */ + new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; + } + export var Draggable: DraggableStatic; + + + export interface Draggable extends IEventPowered { + /** + * Enables the dragging ability. + */ + enable(): void; + + /** + * Disables the dragging ability. + */ + disable(): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Draggable; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + fire(type: string, data?: any): Draggable; + addEventListener(eventMap: any, context?: any): Draggable; + removeEventListener(eventMap?: any, context?: any): Draggable; + clearAllEventListeners(): Draggable; + on(eventMap: any, context?: any): Draggable; + off(eventMap?: any, context?: any): Draggable; + } +} + + + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function featureGroup(layers?: T[]): FeatureGroup; + + + export interface FeatureGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): FeatureGroup; + } + export var FeatureGroup: FeatureGroupStatic; + + export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { + /** + * Binds a popup with a particular HTML content to a click on any layer from the + * group that has a bindPopup method. + */ + bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; + + /** + * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates + * of its children). + */ + getBounds(): LatLngBounds; + + /** + * Sets the given path options to each layer of the group that has a setStyle method. + */ + setStyle(style: PathOptions): FeatureGroup; + + /** + * Brings the layer group to the top of all other layers. + */ + bringToFront(): FeatureGroup; + + /** + * Brings the layer group to the bottom of all other layers. + */ + bringToBack(): FeatureGroup; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): FeatureGroup; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + fire(type: string, data?: any): FeatureGroup; + addEventListener(eventMap: any, context?: any): FeatureGroup; + removeEventListener(eventMap?: any, context?: any): FeatureGroup; + clearAllEventListeners(): FeatureGroup; + on(eventMap: any, context?: any): FeatureGroup; + off(eventMap?: any, context?: any): FeatureGroup; + } +} + +declare namespace L { + + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + export interface GeoJSONStatic extends ClassStatic { + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + new(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + /** + * Creates a layer from a given GeoJSON feature. + */ + geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; + + /** + * Creates a LatLng object from an array of 2 numbers (latitude, longitude) + * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted + * as (longitude, latitude). + */ + coordsToLatLng(coords: number[], reverse?: boolean): LatLng; + + /** + * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates + * array. levelsDeep specifies the nesting level (0 is for an array of points, + * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to + * true, the numbers will be interpreted as (longitude, latitude). + */ + coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; + } + export var GeoJSON: GeoJSONStatic; + + export interface GeoJSON extends FeatureGroup { + /** + * Adds a GeoJSON object to the layer. + */ + addData(data: any): boolean; + + /** + * Changes styles of GeoJSON vector layers with the given style function. + */ + setStyle(style: (featureData: any) => any): GeoJSON; + + /** + * Changes styles of GeoJSON vector layers with the given style options. + */ + setStyle(style: PathOptions): GeoJSON; + + /** + * Resets the the given vector layer's style to the original GeoJSON style, + * useful for resetting style after hover events. + */ + resetStyle(layer: Path): GeoJSON; + } +} + +declare namespace L { + export interface GeoJSONOptions { + /** + * Function that will be used for creating layers for GeoJSON points (if not + * specified, simple markers will be created). + */ + pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; + + /** + * Function that will be used to get style options for vector layers created + * for GeoJSON features. + */ + style?: (featureData: any) => any; + + /** + * Function that will be called on each created feature layer. Useful for attaching + * events and popups to features. + */ + onEachFeature?: (featureData: any, layer: ILayer) => void; + + /** + * Function that will be used to decide whether to show a feature or not. + */ + filter?: (featureData: any, layer: ILayer) => boolean; + + /** + * Function that will be used for converting GeoJSON coordinates to LatLng points + * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] + * values in degrees). + */ + coordsToLatLng?: (coords: any[]) => LatLng[]; + } +} + + + + +declare namespace L { + + /** + * Creates an icon instance with the given options. + */ + function icon(options: IconOptions): Icon; + + export interface IconStatic extends ClassStatic { + /** + * Creates an icon instance with the given options. + */ + new(options: IconOptions): Icon; + + Default: { + /** + * Creates a default icon instance with the given options. + */ + new(options?: IconOptions): Icon.Default; + + imagePath: string; + }; + } + export var Icon: IconStatic; + + export interface Icon { + } + + namespace Icon { + /** + * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses + * for markers by default. + */ + export interface Default extends Icon { + } + } +} + +declare namespace L { + + export interface IconOptions { + + /** + * (required) The URL to the icon image (absolute or relative to your script + * path). + */ + iconUrl?: string; + + /** + * The URL to a retina sized version of the icon image (absolute or relative to + * your script path). Used for Retina screen devices. + */ + iconRetinaUrl?: string; + + /** + * Size of the icon image in pixels. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * The URL to the icon shadow image. If not specified, no shadow image will be + * created. + */ + shadowUrl?: string; + + /** + * The URL to the retina sized version of the icon shadow image. If not specified, + * no shadow image will be created. Used for Retina screen devices. + */ + shadowRetinaUrl?: string; + + /** + * Size of the shadow image in pixels. + */ + shadowSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the shadow (relative to its top left corner) + * (the same as iconAnchor if not specified). + */ + shadowAnchor?: Point|[number, number]; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to both icon and shadow images. Empty by default. + */ + className?: string; + } +} + +declare namespace L { + + export interface IControl { + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ICRS { + + /** + * Projection that this CRS uses. + */ + projection: IProjection; + + /** + * Transformation that this CRS uses to turn projected coordinates into screen + * coordinates for a particular tile service. + */ + transformation: Transformation; + + /** + * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). + */ + code: string; + + /** + * Projects geographical coordinates on a given zoom into pixel coordinates. + */ + latLngToPoint(latlng: LatLng, zoom: number): Point; + + /** + * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom + * into geographical coordinates. + */ + pointToLatLng(point: Point, zoom: number): LatLng; + + /** + * Projects geographical coordinates into coordinates in units accepted + * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). + */ + project(latlng: LatLng): Point; + + /** + * Returns the scale used when transforming projected coordinates into pixel + * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for + * Mercator-based CRS. + */ + scale(zoom: number): number; + + /** + * Returns the size of the world in pixels for a particular zoom. + */ + getSize(zoom: number): Point; + + } +} + +declare namespace L { + + export interface IEventPowered { + + /** + * Adds a listener function (fn) to a particular event type of the object. You + * can optionally specify the context of the listener (object the this keyword + * will point to). You can also pass several space-separated types (e.g. 'click + * dblclick'). + */ + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * The same as above except the listener will only get fired once and then removed. + */ + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + /** + * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} + */ + addEventListener(eventMap: any, context?: any): T; + + /** + * Removes a previously added listener function. If no function is specified, + * it will remove all the listeners of that particular event from the object. + */ + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Removes a set of type/listener pairs. + */ + removeEventListener(eventMap?: any, context?: any): T; + + /** + * Returns true if a particular event type has some listeners attached to it. + */ + hasEventListeners(type: string): boolean; + + /** + * Fires an event of the specified type. You can optionally provide an data object + * — the first argument of the listener function will contain its properties. + */ + fireEvent(type: string, data?: any): T; + + /** + * Removes all listeners to all events on the object. + */ + clearAllEventListeners(): T; + + /** + * Alias to addEventListener. + */ + on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to addEventListener. + */ + on(eventMap: any, context?: any): T; + + /** + * Alias to addOneTimeEventListener. + */ + once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(eventMap?: any, context?: any): T; + + /** + * Alias to fireEvent. + */ + fire(type: string, data?: any): T; + } +} + +declare namespace L { + + export interface IHandler { + + /** + * Enables the handler. + */ + enable(): void; + + /** + * Disables the handler. + */ + disable(): void; + + /** + * Returns true if the handler is enabled. + */ + enabled(): boolean; + } + + export interface Handler { + initialize(map: Map): void; + } +} + +declare namespace L { + + export interface ILayer { + + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + namespace Mixin { + export interface LeafletMixinEvents extends IEventPowered { + } + + export var Events: LeafletMixinEvents; + } +} + +declare namespace L { + + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + + export interface ImageOverlayStatic extends ClassStatic { + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + } + export var ImageOverlay: ImageOverlayStatic; + + export interface ImageOverlay extends ILayer { + /** + * Adds the overlay to the map. + */ + addTo(map: Map): ImageOverlay; + + /** + * Sets the opacity of the overlay. + */ + setOpacity(opacity: number): ImageOverlay; + + /** + * Changes the URL of the image. + */ + setUrl(imageUrl: string): ImageOverlay; + + /** + * Brings the layer to the top of all overlays. + */ + bringToFront(): ImageOverlay; + + /** + * Brings the layer to the bottom of all overlays. + */ + bringToBack(): ImageOverlay; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ImageOverlayOptions { + + /** + * The opacity of the image overlay. + */ + opacity?: number; + } +} + +declare namespace L { + + export interface IProjection { + + /** + * Projects geographical coordinates into a 2D point. + */ + project(latlng: LatLng): Point; + + /** + * The inverse of project. Projects a 2D point into geographical location. + */ + unproject(point: Point): LatLng; + } +} + +declare namespace L { + + /** + * A constant that represents the Leaflet version in use. + */ + export var version: string; + + /** + * This method restores the L global variale to the original value it had + * before Leaflet inclusion, and returns the real Leaflet namespace. + */ + export function noConflict(): typeof L; +} + +declare namespace L { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(coords: LatLngExpression): LatLng; + + export interface LatLngStatic { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(coords: LatLngExpression): LatLng; + + /** + * A multiplier for converting degrees into radians. + * + * Value: Math.PI / 180. + */ + DEG_TO_RAD: number; + + /** + * A multiplier for converting radians into degrees. + * + * Value: 180 / Math.PI. + */ + RAD_TO_DEG: number; + + /** + * Max margin of error for the equality check. + * + * Value: 1.0E-9. + */ + MAX_MARGIN: number; + } + export var LatLng: LatLngStatic; + + export interface LatLng { + /** + * Returns the distance (in meters) to the given LatLng calculated using the + * Haversine formula. See description on wikipedia + */ + distanceTo(otherLatlng: LatLngExpression): number; + + /** + * Returns true if the given LatLng point is at the same position (within a small + * margin of error). + */ + equals(otherLatlng: LatLngExpression): boolean; + + /** + * Returns a string representation of the point (for debugging purposes). + */ + toString(): string; + + /** + * Returns a new LatLng object with the longitude wrapped around left and right + * boundaries (-180 to 180 by default). + */ + wrap(left: number, right: number): LatLng; + + /** + * Latitude in degrees. + */ + lat: number; + + /** + * Longitude in degrees. + */ + lng: number; + } +} + +declare namespace L { + + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + + export interface LatLngBoundsStatic { + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + new(latlngs: LatLngBoundsExpression): LatLngBounds; + } + export var LatLngBounds: LatLngBoundsStatic; + + export interface LatLngBounds { + /** + * Extends the bounds to contain the given point. + */ + extend(latlng: LatLngExpression): LatLngBounds; + + /** + * Extends the bounds to contain the given bounds. + */ + extend(latlng: LatLngBoundsExpression): LatLngBounds; + + /** + * Returns the south-west point of the bounds. + */ + getSouthWest(): LatLng; + + /** + * Returns the north-east point of the bounds. + */ + getNorthEast(): LatLng; + + /** + * Returns the north-west point of the bounds. + */ + getNorthWest(): LatLng; + + /** + * Returns the south-east point of the bounds. + */ + getSouthEast(): LatLng; + + /** + * Returns the west longitude in degrees of the bounds. + */ + getWest(): number; + + /** + * Returns the east longitude in degrees of the bounds. + */ + getEast(): number; + + /** + * Returns the north latitude in degrees of the bounds. + */ + getNorth(): number; + + /** + * Returns the south latitude in degrees of the bounds. + */ + getSouth(): number; + + /** + * Returns the center point of the bounds. + */ + getCenter(): LatLng; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(latlng: LatLngExpression): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle is equivalent (within a small margin of error) + * to the given bounds. + */ + equals(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' + * format. Useful for sending requests to web services that return geo data. + */ + toBBoxString(): string; + + /** + * Returns bigger bounds created by extending the current bounds by a given + * percentage in each direction. + */ + pad(bufferRatio: number): LatLngBounds; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + } +} + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function layerGroup(layers?: T[]): LayerGroup; + + + export interface LayerGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): LayerGroup; + } + export var LayerGroup: LayerGroupStatic; + + export interface LayerGroup extends ILayer { + /** + * Adds the group of layers to the map. + */ + addTo(map: Map): LayerGroup; + + /** + * Adds a given layer to the group. + */ + addLayer(layer: T): LayerGroup; + + /** + * Removes a given layer from the group. + */ + removeLayer(layer: T): LayerGroup; + + /** + * Removes a given layer of the given id from the group. + */ + removeLayer(id: string): LayerGroup; + + /** + * Returns true if the given layer is currently added to the group. + */ + hasLayer(layer: T): boolean; + + /** + * Returns the layer with the given id. + */ + getLayer(id: string): T; + + /** + * Returns an array of all the layers added to the group. + */ + getLayers(): T[]; + + /** + * Removes all the layers from the group. + */ + clearLayers(): LayerGroup; + + /** + * Iterates over the layers of the group, optionally specifying context of + * the iterator function. + */ + eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; + + /** + * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + */ + toGeoJSON(): any; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + + +declare namespace L { + + export interface LayersOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * + * Default value: 'topright'. + */ + position?: string; + + /** + * If true, the control will be collapsed into an icon and expanded on mouse hover + * or touch. + * + * Default value: true. + */ + collapsed?: boolean; + + /** + * If true, the control will assign zIndexes in increasing order to all of its + * layers so that the order is preserved when switching them on/off. + * + * Default value: true. + */ + autoZIndex?: boolean; + + } +} + +declare namespace L { + + export interface LeafletErrorEvent extends LeafletEvent { + + /** + * Error message. + */ + message: string; + + /** + * Error code (if applicable). + */ + code: number; + } +} + +declare namespace L { + + export interface LeafletEvent { + + /** + * The event type (e.g. 'click'). + */ + type: string; + + /** + * The object that fired the event. + */ + target: any; + } +} + +declare namespace L { + + export interface LeafletGeoJSONEvent extends LeafletEvent { + + /** + * The layer for the GeoJSON feature that is being added to the map. + */ + layer: ILayer; + + /** + * GeoJSON properties of the feature. + */ + properties: any; + + /** + * GeoJSON geometry type of the feature. + */ + geometryType: string; + + /** + * GeoJSON ID of the feature (if present). + */ + id: string; + } +} + +declare namespace L { + + export interface LeafletLayerEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + } +} + +declare namespace L { + + export interface LeafletLayersControlEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + + /** + * The name of the layer that was added or removed. + */ + name: string; + } +} + +declare module L { + + export interface LeafletLocationEvent extends LeafletEvent { + + /** + * Detected geographical location of the user. + */ + latlng: LatLng; + + /** + * Geographical bounds of the area user is located in (with respect to the accuracy + * of location). + */ + bounds: LatLngBounds; + + /** + * Accuracy of location in meters. + */ + accuracy: number; + + /** + * Height of the position above the WGS84 ellipsoid in meters. + */ + altitude: number; + + /** + * Accuracy of altitude in meters. + */ + altitudeAccuracy: number; + + /** + * The direction of travel in degrees counting clockwise from true North. + */ + heading: number; + + /** + * Current velocity in meters per second. + */ + speed: number; + + /** + * The time when the position was acquired. + */ + timestamp: number; + + } +} + +declare namespace L { + + export interface LeafletMouseEvent extends LeafletEvent { + + /** + * The geographical point where the mouse event occured. + */ + latlng: LatLng; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map layer. + */ + layerPoint: Point; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map сontainer. + */ + containerPoint: Point; + + /** + * The original DOM mouse event fired by the browser. + */ + originalEvent: MouseEvent; + } +} + +declare namespace L { + + export interface LeafletPopupEvent extends LeafletEvent { + + /** + * The popup that was opened or closed. + */ + popup: Popup; + } +} + +declare namespace L { + + export interface LeafletDragEndEvent extends LeafletEvent { + + /** + * The distance in pixels the draggable element was moved by. + */ + distance: number; + } +} + +declare namespace L { + + export interface LeafletResizeEvent extends LeafletEvent { + + /** + * The old size before resize event. + */ + oldSize: Point; + + /** + * The new size after the resize event. + */ + newSize: Point; + } +} + +declare namespace L { + + export interface LeafletTileEvent extends LeafletEvent { + + /** + * The tile element (image). + */ + tile: HTMLElement; + + /** + * The source URL of the tile. + */ + url: string; + } +} + +declare namespace L { + + namespace LineUtil { + + /** + * Dramatically reduces the number of points in a polyline while retaining + * its shape and returns a new array of simplified points. Used for a huge performance + * boost when processing/displaying Leaflet polylines for each zoom level + * and also reducing visual noise. tolerance affects the amount of simplification + * (lesser value means higher quality but slower and with more points). Also + * released as a separated micro-library Simplify.js. + */ + export function simplify(points: Point[], tolerance: number): Point[]; + + /** + * Returns the distance between point p and segment p1 to p2. + */ + export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; + + /** + * Returns the closest point from a point p on a segment p1 to p2. + */ + export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; + + /** + * Clips the segment a to b by rectangular bounds (modifying the segment points + * directly!). Used by Leaflet to only show polyline points that are on the screen + * or near, increasing performance. + */ + export function clipSegment(a: Point, b: Point, bounds: Bounds): void; + + } +} + +declare namespace L { + + export interface LocateOptions { + + /** + * If true, starts continous watching of location changes (instead of detecting + * it once) using W3C watchPosition method. You can later stop watching using + * map.stopLocate() method. + * + * Default value: false. + */ + watch?: boolean; + + /** + * If true, automatically sets the map view to the user location with respect + * to detection accuracy, or to world view if geolocation failed. + * + * Default value: false. + */ + setView?: boolean; + + /** + * The maximum zoom for automatic view setting when using `setView` option. + * + * Default value: Infinity. + */ + maxZoom?: number; + + /** + * Number of millisecond to wait for a response from geolocation before firing + * a locationerror event. + * + * Default value: 10000. + */ + timeout?: number; + + /** + * Maximum age of detected location. If less than this amount of milliseconds + * passed since last geolocation response, locate will return a cached location. + * + * Default value: 0. + */ + maximumAge?: number; + + /** + * Enables high accuracy, see description in the W3C spec. + * + * Default value: false. + */ + enableHighAccuracy?: boolean; + } +} + +declare namespace L { + + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + */ + function map(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + */ + function map(id: string, options?: Map.MapOptions): Map; + + + export interface MapStatic extends ClassStatic { + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: string, options?: Map.MapOptions): Map; + } + export var Map: MapStatic; + + export interface Map extends IEventPowered { + // Methods for Modifying Map State + + /** + * Sets the view of the map (geographical center and zoom) with the given + * animation options. + */ + setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets the zoom of the map. + */ + setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Increases the zoom of the map by delta (1 by default). + */ + zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Decreases the zoom of the map by delta (1 by default). + */ + zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Zooms the map while keeping a specified point on the map stationary + * (e.g. used internally for scroll zoom and double-click zoom). + */ + setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets a map view that contains the given geographical bounds with the maximum + * zoom level possible. + */ + fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; + + /** + * Sets a map view that mostly contains the whole world with the maximum zoom + * level possible. + */ + fitWorld(options?: Map.FitBoundsOptions): Map; + + /** + * Pans the map to a given center. Makes an animated pan if new center is not more + * than one screen away from the current one. + */ + panTo(latlng: LatLngExpression, options?: PanOptions): Map; + + /** + * Pans the map to the closest view that would lie inside the given bounds (if + * it's not already). + */ + panInsideBounds(bounds: LatLngBounds): Map; + + /** + * Pans the map by a given number of pixels (animated). + */ + panBy(point: Point, options?: PanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + * If options.pan is false, panning will not occur. + */ + invalidateSize(options: Map.ZoomPanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + */ + invalidateSize(animate: boolean): Map; + + /** + * Restricts the map view to the given bounds (see map maxBounds option), + * passing the given animation options through to `setView`, if required. + */ + setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; + + /** + * Tries to locate the user using Geolocation API, firing locationfound event + * with location data on success or locationerror event on failure, and optionally + * sets the map view to the user location with respect to detection accuracy + * (or to the world view if geolocation failed). See Locate options for more + * details. + */ + locate(options?: LocateOptions): Map; + + /** + * Stops watching location previously initiated by map.locate({watch: true}) + * and aborts resetting the map view if map.locate was called with {setView: true}. + */ + stopLocate(): Map; + + /** + * Destroys the map and clears all related event listeners. + */ + remove(): Map; + + // Methods for Getting Map State + + /** + * Returns the geographical center of the map view. + */ + getCenter(): LatLng; + + /** + * Returns the current zoom of the map view. + */ + getZoom(): number; + + /** + * Returns the minimum zoom level of the map. + */ + getMinZoom(): number; + + /** + * Returns the maximum zoom level of the map. + */ + getMaxZoom(): number; + + /** + * Returns the LatLngBounds of the current map view. + */ + getBounds(): LatLngBounds; + + /** + * Returns the maximum zoom level on which the given bounds fit to the map view + * in its entirety. If inside (optional) is set to true, the method instead returns + * the minimum zoom level on which the map view fits into the given bounds in its + * entirety. + */ + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + + /** + * Returns the current size of the map container. + */ + getSize(): Point; + + /** + * Returns the bounds of the current map view in projected pixel coordinates + * (sometimes useful in layer and overlay implementations). + */ + getPixelBounds(): Bounds; + + /** + * Returns the projected pixel coordinates of the top left point of the map layer + * (useful in custom layer and overlay implementations). + */ + getPixelOrigin(): Point; + + // Methods for Layers and Controls + + /** + * Adds the given layer to the map. If optional insertAtTheBottom is set to true, + * the layer is inserted under all others (useful when switching base tile layers). + */ + addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; + + /** + * Removes the given layer from the map. + */ + removeLayer(layer: ILayer): Map; + + /** + * Returns true if the given layer is currently added to the map. + */ + hasLayer(layer: ILayer): boolean; + + /** + * Opens the specified popup while closing the previously opened (to make sure + * only one is opened at one time for usability). + */ + openPopup(popup: Popup): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Closes the popup previously opened with openPopup (or the given one). + */ + closePopup(popup?: Popup): Map; + + /** + * Adds the given control to the map. + */ + addControl(control: IControl): Map; + + /** + * Removes the given control from the map. + */ + removeControl(control: IControl): Map; + + // Conversion Methods + + /** + * Returns the map layer point that corresponds to the given geographical coordinates + * (useful for placing overlays on the map). + */ + latLngToLayerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map layer point. + */ + layerPointToLatLng(point: Point): LatLng; + + /** + * Converts the point relative to the map container to a point relative to the + * map layer. + */ + containerPointToLayerPoint(point: Point): Point; + + /** + * Converts the point relative to the map layer to a point relative to the map + * container. + */ + layerPointToContainerPoint(point: Point): Point; + + /** + * Returns the map container point that corresponds to the given geographical + * coordinates. + */ + latLngToContainerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map container point. + */ + containerPointToLatLng(point: Point): LatLng; + + /** + * Projects the given geographical coordinates to absolute pixel coordinates + * for the given zoom level (current zoom level by default). + */ + project(latlng: LatLngExpression, zoom?: number): Point; + + /** + * Projects the given absolute pixel coordinates to geographical coordinates + * for the given zoom level (current zoom level by default). + */ + unproject(point: Point, zoom?: number): LatLng; + + /** + * Returns the pixel coordinates of a mouse click (relative to the top left corner + * of the map) given its event object. + */ + mouseEventToContainerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the pixel coordinates of a mouse click relative to the map layer given + * its event object. + */ + mouseEventToLayerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the geographical coordinates of the point the mouse clicked on given + * the click's event object. + */ + mouseEventToLatLng(event: LeafletMouseEvent): LatLng; + + // Other Methods + + /** + * Returns the container element of the map. + */ + getContainer(): HTMLElement; + + /** + * Returns an object with different map panes (to render overlays in). + */ + getPanes(): MapPanes; + + // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? + /** + * Runs the given callback when the map gets initialized with a place and zoom, + * or immediately if it happened already, optionally passing a function context. + */ + whenReady(fn: (map: Map) => void, context?: any): Map; + + // Properties + + /** + * Map dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + /** + * Touch zoom handler. + */ + touchZoom: IHandler; + + /** + * Double click zoom handler. + */ + doubleClickZoom: IHandler; + + /** + * Scroll wheel zoom handler. + */ + scrollWheelZoom: IHandler; + + /** + * Box (shift-drag with mouse) zoom handler. + */ + boxZoom: IHandler; + + /** + * Keyboard navigation handler. + */ + keyboard: IHandler; + + /** + * Mobile touch hacks (quick tap and touch hold) handler. + */ + tap: IHandler; + + /** + * Zoom control. + */ + zoomControl: Control.Zoom; + + /** + * Attribution control. + */ + attributionControl: Control.Attribution; + + /** + * Map state options + */ + options: Map.MapOptions; + + /** + * Iterates over the layers of the map, optionally specifying context + * of the iterator function. + */ + eachLayer(fn: (layer: ILayer) => void, context?: any): Map; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Map; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; + removeEventListener(eventMap?: any, context?: any): Map; + clearAllEventListeners(): Map; + on(eventMap: any, context?: any): Map; + off(eventMap?: any, context?: any): Map; + } +} + +declare namespace L.Map { + + export interface MapOptions { + + // Map State Options + + /** + * Initial geographical center of the map. + */ + center?: LatLng; + + /** + * Initial map zoom. + */ + zoom?: number; + + /** + * Layers that will be added to the map initially. + */ + layers?: ILayer[]; + + /** + * Minimum zoom level of the map. Overrides any minZoom set on map layers. + */ + minZoom?: number; + + /** + * Maximum zoom level of the map. This overrides any maxZoom set on map layers. + */ + maxZoom?: number; + + /** + * When this option is set, the map restricts the view to the given geographical + * bounds, bouncing the user back when he tries to pan outside the view, and also + * not allowing to zoom out to a view that's larger than the given bounds (depending + * on the map size). To set the restriction dynamically, use setMaxBounds method + */ + maxBounds?: LatLngBounds; + + /** + * Coordinate Reference System to use. Don't change this if you're not sure + * what it means. + * + * Default value: L.CRS.EPSG3857. + */ + crs?: ICRS; + + // Interaction Options + + /** + * Whether the map be draggable with mouse/touch or not. + * + * Default value: true. + */ + dragging?: boolean; + + /** + * Whether the map can be zoomed by touch-dragging with two fingers. + * + * Default value: true. + */ + touchZoom?: boolean; + + /** + * Whether the map can be zoomed by using the mouse wheel. + * If passed 'center', it will zoom to the center of the view regardless of + * where the mouse was. + * + * Default value: true. + */ + scrollWheelZoom?: boolean; + + /** + * Whether the map can be zoomed in by double clicking on it and zoomed out + * by double clicking while holding shift. + * If passed 'center', double-click zoom will zoom to the center of the view + * regardless of where the mouse was. + * + * Default value: true. + */ + doubleClickZoom?: boolean; + + /** + * Whether the map can be zoomed to a rectangular area specified by dragging + * the mouse while pressing shift. + * + * Default value: true. + */ + boxZoom?: boolean; + + /** + * Enables mobile hacks for supporting instant taps (fixing 200ms click delay + * on iOS/Android) and touch holds (fired as contextmenu events). + * + * Default value: true. + */ + tap?: boolean; + + /** + * The max number of pixels a user can shift his finger during touch for it + * to be considered a valid tap. + * + * Default value: 15. + */ + tapTolerance?: number; + + /** + * Whether the map automatically handles browser window resize to update itself. + * + * Default value: true. + */ + trackResize?: boolean; + + /** + * With this option enabled, the map tracks when you pan to another "copy" of + * the world and seamlessly jumps to the original one so that all overlays like + * markers and vector layers are still visible. + * + * Default value: false. + */ + worldCopyJump?: boolean; + + /** + * Set it to false if you don't want popups to close when user clicks the map. + * + * Default value: true. + */ + closePopupOnClick?: boolean; + + // Keyboard Navigation Options + + /** + * Makes the map focusable and allows users to navigate the map with keyboard + * arrows and +/- keys. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Amount of pixels to pan when pressing an arrow key. + * + * Default value: 80. + */ + keyboardPanOffset?: number; + + /** + * Number of zoom levels to change when pressing + or - key. + * + * Default value: 1. + */ + keyboardZoomOffset?: number; + + // Panning Inertia Options + + /** + * If enabled, panning of the map will have an inertia effect where the map builds + * momentum while dragging and continues moving in the same direction for some + * time. Feels especially nice on touch devices. + * + * Default value: true. + */ + inertia?: boolean; + + /** + * The rate with which the inertial movement slows down, in pixels/second2. + * + * Default value: 3000. + */ + inertiaDeceleration?: number; + + /** + * Max speed of the inertial movement, in pixels/second. + * + * Default value: 1500. + */ + inertiaMaxSpeed?: number; + + /** + * Amount of milliseconds that should pass between stopping the movement and + * releasing the mouse or touch to prevent inertial movement. + * + * Default value: 32 for touch devices and 14 for the rest. + */ + inertiaThreshold?: number; + + // Control options + + /** + * Whether the zoom control is added to the map by default. + * + * Default value: true. + */ + zoomControl?: boolean; + + /** + * Whether the attribution control is added to the map by default. + * + * Default value: true. + */ + attributionControl?: boolean; + + // Animation options + + /** + * Whether the tile fade animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + fadeAnimation?: boolean; + + /** + * Whether the tile zoom animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + zoomAnimation?: boolean; + + /** + * Won't animate zoom if the zoom difference exceeds this value. + * + * Default value: 4. + */ + zoomAnimationThreshold?: number; + + /** + * Whether markers animate their zoom with the zoom animation, if disabled + * they will disappear for the length of the animation. By default it's enabled + * in all browsers that support CSS3 Transitions except Android. + */ + markerZoomAnimation?: boolean; + + /** + * Set it to false if you don't want the map to zoom beyond min/max zoom + * and then bounce back when pinch-zooming. + * + * Default value: true. + */ + bounceAtZoomLimits?: boolean; + } + + export interface ZoomOptions { + /** + * If not specified, zoom animation will happen if the zoom origin is inside the current view. + * If true, the map will attempt animating zoom disregarding where zoom origin is. + * Setting false will make it always reset the view completely without animation. + */ + animate?: boolean; + } + + export interface ZoomPanOptions { + + /** + * If true, the map view will be completely reset (without any animations). + * + * Default value: false. + */ + reset?: boolean; + + /** + * Sets the options for the panning (without the zoom change) if it occurs. + */ + pan?: PanOptions; + + /** + * Sets the options for the zoom change if it occurs. + */ + zoom?: ZoomOptions; + + /** + * An equivalent of passing animate to both zoom and pan options (see below). + */ + animate?: boolean; + + /** + * If true, it will delay moveend event so that it doesn't happen many times in a row. + */ + debounceMoveend?: boolean; + } + + export interface FitBoundsOptions extends ZoomPanOptions { + + /** + * Sets the amount of padding in the top left corner of a map container that + * shouldn't be accounted for when setting the view to fit bounds. Useful if + * you have some control overlays on the map like a sidebar and you don't + * want them to obscure objects you're zooming to. + * + * Default value: [0, 0]. + */ + paddingTopLeft?: Point; + + /** + * The same for bottom right corner of the map. + * + * Default value: [0, 0]. + */ + paddingBottomRight?: Point; + + /** + * Equivalent of setting both top left and bottom right padding to the same value. + * + * Default value: [0, 0]. + */ + padding?: Point; + + /** + * The maximum possible zoom to use. + * + * Default value: null + */ + maxZoom?: number; + } +} + +declare namespace L { + + export interface MapPanes { + + /** + * Pane that contains all other map panes. + */ + mapPane: HTMLElement; + + /** + * Pane for tile layers. + */ + tilePane: HTMLElement; + + /** + * Pane that contains all the panes except tile pane. + */ + objectsPane: HTMLElement; + + /** + * Pane for overlay shadows (e.g. marker shadows). + */ + shadowPane: HTMLElement; + + /** + * Pane for overlays like polylines and polygons. + */ + overlayPane: HTMLElement; + + /** + * Pane for marker icons. + */ + markerPane: HTMLElement; + + /** + * Pane for popups. + */ + popupPane: HTMLElement; + } +} + +declare namespace L { + + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; + + var Marker: { + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + new(latlng: LatLngExpression, options?: MarkerOptions): Marker; + }; + + export interface Marker extends ILayer, IEventPowered { + /** + * Adds the marker to the map. + */ + addTo(map: Map): Marker; + + /** + * Returns the current geographical position of the marker. + */ + getLatLng(): LatLng; + + /** + * Changes the marker position to the given point. + */ + setLatLng(latlng: LatLngExpression): Marker; + + /** + * Changes the marker icon. + */ + setIcon(icon: Icon): Marker; + + /** + * Changes the zIndex offset of the marker. + */ + setZIndexOffset(offset: number): Marker; + + /** + * Changes the opacity of the marker. + */ + setOpacity(opacity: number): Marker; + + /** + * Updates the marker position, useful if coordinates of its latLng object + * were changed directly. + */ + update(): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(html: string, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(popup: Popup, options?: PopupOptions): Marker; + + /** + * Unbinds the popup previously bound to the marker with bindPopup. + */ + unbindPopup(): Marker; + + /** + * Opens the popup previously bound by the bindPopup method. + */ + openPopup(): Marker; + + /** + * Returns the popup previously bound by the bindPopup method. + */ + getPopup(): Popup; + + /** + * Closes the bound popup of the marker if it's opened. + */ + closePopup(): Marker; + + /** + * Toggles the popup previously bound by the bindPopup method. + */ + togglePopup(): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(html: string, options?: PopupOptions): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). + */ + toGeoJSON(): any; + + /** + * Marker dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Marker; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + fire(type: string, data?: any): Marker; + addEventListener(eventMap: any, context?: any): Marker; + removeEventListener(eventMap?: any, context?: any): Marker; + clearAllEventListeners(): Marker; + on(eventMap: any, context?: any): Marker; + off(eventMap?: any, context?: any): Marker; + } +} + +declare namespace L { + + export interface MarkerOptions { + + /** + * Icon class to use for rendering the marker. See Icon documentation for details + * on how to customize the marker icon. + * + * Default value: new L.Icon.Default(). + */ + icon?: Icon; + + /** + * If false, the marker will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Whether the marker is draggable with mouse/touch or not. + * + * Default value: false. + */ + draggable?: boolean; + + /** + * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Text for the browser tooltip that appear on marker hover (no tooltip by default). + * + * Default value: ''. + */ + title?: string; + + /** + * Text for the alt attribute of the icon image (useful for accessibility). + * + * Default value: ''. + */ + alt?: string; + + /** + * By default, marker images zIndex is set automatically based on its latitude. + * You this option if you want to put the marker on top of all others (or below), + * specifying a high value like 1000 (or high negative value, respectively). + * + * Default value: 0. + */ + zIndexOffset?: number; + + /** + * The opacity of the marker. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * If true, the marker will get on top of others when you hover the mouse over it. + * + * Default value: false. + */ + riseOnHover?: boolean; + + /** + * The z-index offset used for the riseOnHover feature. + * + * Default value: 250. + */ + riseOffset?: number; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + + export interface MultiPolygonStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + } + export var MultiPolygon: MultiPolygonStatic; + + export interface MultiPolygon extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolygon; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolygon; + + /** + * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). + */ + toGeoJSON(): any; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + + export interface MultiPolylineStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + } + export var MultiPolyline: MultiPolylineStatic; + + export interface MultiPolyline extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolyline; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolyline; + + /** + * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). + */ + toGeoJSON(): any; + } +} + +declare namespace L { + + export interface PanOptions { + + /** + * If true, panning will always be animated if possible. If false, it will not + * animate panning, either resetting the map view if panning more than a screen + * away, or just setting a new offset for the map pane (except for `panBy` + * which always does the latter). + */ + animate?: boolean; + + /** + * Duration of animated panning. + * + * Default value: 0.25. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic + * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. + * + * Default value: 0.25. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + * + * Default value: false. + */ + noMoveStart?: boolean; + } +} + +declare namespace L { + + export interface Path extends ILayer, IEventPowered { + + /** + * Adds the layer to the map. + */ + addTo(map: Map): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(html: string, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(popup: Popup, options?: PopupOptions): Path; + + /** + * Unbinds the popup previously bound to the path with bindPopup. + */ + unbindPopup(): Path; + + /** + * Opens the popup previously bound by the bindPopup method in the given point, + * or in one of the path's points if not specified. + */ + openPopup(latlng?: LatLngExpression): Path; + + /** + * Closes the path's bound popup if it is opened. + */ + closePopup(): Path; + + /** + * Changes the appearance of a Path based on the options in the Path options object. + */ + setStyle(object: PathOptions): Path; + + /** + * Returns the LatLngBounds of the path. + */ + getBounds(): LatLngBounds; + + /** + * Brings the layer to the top of all path layers. + */ + bringToFront(): Path; + + /** + * Brings the layer to the bottom of all path layers. + */ + bringToBack(): Path; + + /** + * Redraws the layer. Sometimes useful after you changed the coordinates that + * the path uses. + */ + redraw(): Path; + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Path; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + fire(type: string, data?: any): Path; + addEventListener(eventMap: any, context?: any): Path; + removeEventListener(eventMap?: any, context?: any): Path; + clearAllEventListeners(): Path; + on(eventMap: any, context?: any): Path; + off(eventMap?: any, context?: any): Path; + } + + export namespace Path { + /** + * True if SVG is used for vector rendering (true for most modern browsers). + */ + export var SVG: boolean; + + /** + * True if VML is used for vector rendering (IE 6-8). + */ + export var VML: boolean; + + /** + * True if Canvas is used for vector rendering (Android 2). You can also force + * this by setting global variable L_PREFER_CANVAS to true before the Leaflet + * include on your page — sometimes it can increase performance dramatically + * when rendering thousands of circle markers, but currently suffers from + * a bug that causes removing such layers to be extremely slow. + */ + export var CANVAS: boolean; + + /** + * How much to extend the clip area around the map view (relative to its size, + * e.g. 0.5 is half the screen in each direction). Smaller values mean that you + * will see clipped ends of paths while you're dragging the map, and bigger values + * decrease drawing performance. + */ + export var CLIP_PADDING: number; + } +} + +declare namespace L { + + export interface PathOptions { + + /** + * Whether to draw stroke along the path. Set it to false to disable borders on + * polygons or circles. + * + * Default value: true. + */ + stroke?: boolean; + + /** + * Stroke color. + * + * Default value: '#03f'. + */ + color?: string; + + /** + * Stroke width in pixels. + * + * Default value: 5. + */ + weight?: number; + + /** + * Stroke opacity. + * + * Default value: 0.5. + */ + opacity?: number; + + /** + * Whether to fill the path with color. Set it to false to disable filling on polygons + * or circles. + */ + fill?: boolean; + + /** + * Fill color. + * + * Default value: same as color. + */ + fillColor?: string; + + /** + * Fill opacity. + * + * Default value: 0.2. + */ + fillOpacity?: number; + + /** + * A string that defines the stroke dash pattern. Doesn't work on canvas-powered + * layers (e.g. Android 2). + */ + dashArray?: string; + + /** + * A string that defines shape to be used at the end of the stroke. + * + * Default: null. + */ + lineCap?: string; + + /** + * A string that defines shape to be used at the corners of the stroke. + * + * Default: null. + */ + lineJoin?: string; + + /** + * If false, the vector will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Sets the pointer-events attribute on the path if SVG backend is used. + */ + pointerEvents?: string; + + /** + * Custom class name set on an element. + * + * Default value: ''. + */ + className?: string; + + } +} + +declare namespace L { + + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + function point(x: number, y: number, round?: boolean): Point; + + export interface PointStatic { + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + new(x: number, y: number, round?: boolean): Point; + } + export var Point: PointStatic; + + export interface Point { + /** + * Returns the result of addition of the current and the given points. + */ + add(otherPoint: Point): Point; + + /** + * Returns the result of subtraction of the given point from the current. + */ + subtract(otherPoint: Point): Point; + + /** + * Returns the result of multiplication of the current point by the given number. + */ + multiplyBy(number: number): Point; + + /** + * Returns the result of division of the current point by the given number. If + * optional round is set to true, returns a rounded result. + */ + divideBy(number: number, round?: boolean): Point; + + /** + * Returns the distance between the current and the given points. + */ + distanceTo(otherPoint: Point): number; + + /** + * Returns a copy of the current point. + */ + clone(): Point; + + /** + * Returns a copy of the current point with rounded coordinates. + */ + round(): Point; + + /** + * Returns true if the given point has the same coordinates. + */ + equals(otherPoint: Point): boolean; + + /** + * Returns a string representation of the point for debugging purposes. + */ + toString(): string; + + /** + * The x coordinate. + */ + x: number; + + /** + * The y coordinate. + */ + y: number; + } +} + +declare namespace L { + + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + + + export interface PolygonStatic extends ClassStatic { + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + } + export var Polygon: PolygonStatic; + + export interface Polygon extends Polyline { + } +} + +declare namespace L { + + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + + export interface PolylineStatic extends ClassStatic { + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + } + export var Polyline: PolylineStatic; + + export interface Polyline extends Path { + /** + * Adds a given point to the polyline. + */ + addLatLng(latlng: LatLngExpression): Polyline; + + /** + * Replaces all the points in the polyline with the given array of geographical + * points. + */ + setLatLngs(latlngs: LatLngBoundsExpression): Polyline; + + /** + * Returns an array of the points in the path. + */ + getLatLngs(): LatLng[]; + + /** + * Allows adding, removing or replacing points in the polyline. Syntax is the + * same as in Array#splice. Returns the array of removed points (if any). + */ + spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; + + /** + * Returns the LatLngBounds of the polyline. + */ + getBounds(): LatLngBounds; + + /** + * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). + */ + toGeoJSON(): any; + } +} + +declare namespace L { + + export interface PolylineOptions extends PathOptions { + + /** + * How much to simplify the polyline on each zoom level. More means better performance + * and smoother look, and less means more accurate representation. + * + * Default value: 1.0. + */ + smoothFactor?: number; + + /** + * Disabled polyline clipping. + * + * Default value: false. + */ + noClip?: boolean; + } +} + +declare namespace L { + + namespace PolyUtil { + + /** + * Clips the polygon geometry defined by the given points by rectangular bounds. + * Used by Leaflet to only show polygon points that are on the screen or near, + * increasing performance. Note that polygon points needs different algorithm + * for clipping than polyline, so there's a seperate method for it. + */ + export function clipPolygon(points: Point[], bounds: Bounds): Point[]; + } +} + +declare namespace L { + + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + function popup(options?: PopupOptions, source?: any): Popup; + + export interface PopupStatic extends ClassStatic { + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + new(options?: PopupOptions, source?: any): Popup; + } + export var Popup: PopupStatic; + + export interface Popup extends ILayer { + /** + * Adds the popup to the map. + */ + addTo(map: Map): Popup; + + /** + * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). + */ + openOn(map: Map): Popup; + + /** + * Sets the geographical point where the popup will open. + */ + setLatLng(latlng: LatLngExpression): Popup; + + /** + * Returns the geographical point of popup. + */ + getLatLng(): LatLng; + + /** + * Sets the HTML content of the popup. + */ + setContent(html: string): Popup; + + /** + * Sets the HTML content of the popup. + */ + setContent(el: HTMLElement): Popup; + + /** + * Returns the content of the popup. + */ + getContent(): HTMLElement; + //getContent(): string; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + /** + * Updates the popup content, layout and position. Useful for updating the popup after + * something inside changed, e.g. image loaded. + */ + update(): Popup; + } +} + +declare namespace L { + + export interface PopupOptions { + + /** + * Max width of the popup. + * + * Default value: 300. + */ + maxWidth?: number; + + /** + * Min width of the popup. + * + * Default value: 50. + */ + minWidth?: number; + + /** + * If set, creates a scrollable container of the given height inside a popup + * if its content exceeds it. + */ + maxHeight?: number; + + /** + * Set it to false if you don't want the map to do panning animation to fit the opened + * popup. + * + * Default value: true. + */ + autoPan?: boolean; + + /** + * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. + */ + keepInView?: boolean; + + /** + * Controls the presense of a close button in the popup. + * + * Default value: true. + */ + closeButton?: boolean; + + /** + * The offset of the popup position. Useful to control the anchor of the popup + * when opening it on some overlays. + * + * Default value: new Point(0, 6). + */ + offset?: Point; + + /** + * The margin between the popup and the top left corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingTopLeft?: Point; + + /** + * The margin between the popup and the bottom right corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingBottomRight?: Point; + + /** + * The margin between the popup and the edges of the map view after autopanning + * was performed. + * + * Default value: new Point(5, 5). + */ + autoPanPadding?: Point; + + /** + * Whether to animate the popup on zoom. Disable it if you have problems with + * Flash content inside popups. + * + * Default value: true. + */ + zoomAnimation?: boolean; + + /** + * Set it to false if you want to override the default behavior of the popup + * closing when user clicks the map (set globally by the Map closePopupOnClick + * option). + */ + closeOnClick?: boolean; + + /** + * A custom class name to assign to the popup. + */ + className?: string; + } +} + +declare namespace L { + + export interface PosAnimationStatic extends ClassStatic { + /** + * Creates a PosAnimation object. + */ + new(): PosAnimation; + } + export var PosAnimation: PosAnimationStatic; + + export interface PosAnimation extends IEventPowered { + /** + * Run an animation of a given element to a new position, optionally setting + * duration in seconds (0.25 by default) and easing linearity factor (3rd argument + * of the cubic bezier curve, 0.5 by default) + */ + run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): PosAnimation; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + fire(type: string, data?: any): PosAnimation; + addEventListener(eventMap: any, context?: any): PosAnimation; + removeEventListener(eventMap?: any, context?: any): PosAnimation; + clearAllEventListeners(): PosAnimation; + on(eventMap: any, context?: any): PosAnimation; + off(eventMap?: any, context?: any): PosAnimation; + } +} + +declare namespace L { + + namespace Projection { + + /** + * Spherical Mercator projection — the most common projection for online maps, + * used by almost all free and commercial tile providers. Assumes that Earth + * is a sphere. Used by the EPSG:3857 CRS. + */ + export var SphericalMercator: IProjection; + + /** + * Elliptical Mercator projection — more complex than Spherical Mercator. + * Takes into account that Earth is a geoid, not a perfect sphere. Used by the + * EPSG:3395 CRS. + */ + export var Mercator: IProjection; + + /** + * Equirectangular, or Plate Carree projection — the most simple projection, + * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. + * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple + * CRS. + */ + export var LonLat: IProjection; + } +} + +declare namespace L { + + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; + + export interface RectangleStatic extends ClassStatic { + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + new(bounds: LatLngBounds, options?: PathOptions): Rectangle; + } + export var Rectangle: RectangleStatic; + + export interface Rectangle extends Polygon { + /** + * Redraws the rectangle with the passed bounds. + */ + setBounds(bounds: LatLngBounds): Rectangle; + } +} + + +declare namespace L { + + export interface ScaleOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomleft'. + */ + position?: string; + + /** + * Maximum width of the control in pixels. The width is set dynamically to show + * round values (e.g. 100, 200, 500). + * Default value: 100. + */ + maxWidth?: number; + + /** + * Whether to show the metric scale line (m/km). + * Default value: true. + */ + metric?: boolean; + + /** + * Whether to show the imperial scale line (mi/ft). + * Default value: true. + */ + imperial?: boolean; + + /** + * If true, the control is updated on moveend, otherwise it's always up-to-date + * (updated on move). + * Default value: false. + */ + updateWhenIdle?: boolean; + } +} + +declare namespace L { + + export interface TileLayerStatic extends ClassStatic { + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + new(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + WMS: { + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + new(baseUrl: string, options: WMSOptions): TileLayer.WMS; + }; + + Canvas: { + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + new(options?: TileLayerOptions): TileLayer.Canvas; + }; + } + export var TileLayer: TileLayerStatic; + + export interface TileLayer extends ILayer, IEventPowered { + /** + * Adds the layer to the map. + */ + addTo(map: Map): TileLayer; + + /** + * Brings the tile layer to the top of all tile layers. + */ + bringToFront(): TileLayer; + + /** + * Brings the tile layer to the bottom of all tile layers. + */ + bringToBack(): TileLayer; + + /** + * Changes the opacity of the tile layer. + */ + setOpacity(opacity: number): TileLayer; + + /** + * Sets the zIndex of the tile layer. + */ + setZIndex(zIndex: number): TileLayer; + + /** + * Causes the layer to clear all the tiles and request them again. + */ + redraw(): TileLayer; + + /** + * Updates the layer's URL template and redraws it. + */ + setUrl(urlTemplate: string): TileLayer; + + /** + * Returns the HTML element that contains the tiles for this layer. + */ + getContainer(): HTMLElement; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): TileLayer; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + fire(type: string, data?: any): TileLayer; + addEventListener(eventMap: any, context?: any): TileLayer; + removeEventListener(eventMap?: any, context?: any): TileLayer; + clearAllEventListeners(): TileLayer; + on(eventMap: any, context?: any): TileLayer; + off(eventMap?: any, context?: any): TileLayer; + } + + namespace TileLayer { + export interface WMS extends TileLayer { + /** + * Merges an object with the new parameters and re-requests tiles on the current + * screen (unless noRedraw was set to true). + */ + setParams(params: WMS, noRedraw?: boolean): WMS; + } + + export interface Canvas extends TileLayer { + /** + * You need to define this method after creating the instance to draw tiles; + * canvas is the actual canvas tile on which you can draw, tilePoint represents + * the tile numbers, and zoom is the current zoom. + */ + drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; + + /** + * Calling redraw will cause the drawTile method to be called for all tiles. + * May be used for updating dynamic content drawn on the Canvas + */ + redraw(): Canvas; + } + } + + export interface TileLayerFactory { + + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + (urlTemplate: string, options?: TileLayerOptions): TileLayer; + + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; + + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + canvas(options?: TileLayerOptions): L.TileLayer.Canvas; + } + + export var tileLayer: TileLayerFactory; +} + +declare namespace L { + + export interface TileLayerOptions { + + /** + * Minimum zoom number. + * + * Default value: 0. + */ + minZoom?: number; + + /** + * Maximum zoom number. + * + * Default value: 18. + */ + maxZoom?: number; + + /** + * Maximum zoom number the tiles source has available. If it is specified, + * the tiles on all zoom levels higher than maxNativeZoom will be loaded from + * maxZoom level and auto-scaled. + * + * Default value: null. + */ + maxNativeZoom?: number; + + /** + * Tile size (width and height in pixels, assuming tiles are square). + * + * Default value: 256. + */ + tileSize?: number; + + /** + * Subdomains of the tile service. Can be passed in the form of one string (where + * each letter is a subdomain name) or an array of strings. + * + * Default value: 'abc'. + */ + subdomains?: string[]; + + /** + * URL to the tile image to show in place of the tile that failed to load. + * + * Default value: ''. + */ + errorTileUrl?: string; + + /** + * e.g. "© CloudMade" — the string used by the attribution control, describes + * the layer data. + * + * Default value: ''. + */ + attribution?: string; + + /** + * If true, inverses Y axis numbering for tiles (turn this on for TMS services). + * + * Default value: false. + */ + tms?: boolean; + + /** + * If set to true, the tile coordinates won't be wrapped by world width (-180 + * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this + * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor + * or photo maps). + * + * Default value: false. + */ + continuousWorld?: boolean; + + /** + * If set to true, the tiles just won't load outside the world width (-180 to 180 + * longitude) instead of repeating. + * + * Default value: false. + */ + noWrap?: boolean; + + /** + * The zoom number used in tile URLs will be offset with this value. + * + * Default value: 0. + */ + zoomOffset?: number; + + /** + * If set to true, the zoom number used in tile URLs will be reversed (maxZoom + * - zoom instead of zoom) + * + * Default value: false. + */ + zoomReverse?: boolean; + + /** + * The opacity of the tile layer. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * The explicit zIndex of the tile layer. Not set by default. + */ + zIndex?: number; + + /** + * If true, all the tiles that are not visible after panning are removed (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + unloadInvisibleTiles?: boolean; + + /** + * If false, new tiles are loaded during panning, otherwise only after it (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + updateWhenIdle?: boolean; + + /** + * If true and user is on a retina display, it will request four tiles of half the + * specified size and a bigger zoom level in place of one to utilize the high resolution. + * + * Default value: false. + */ + detectRetina?: boolean; + + /** + * If true, all the tiles that are not visible after panning are placed in a reuse + * queue from which they will be fetched when new tiles become visible (as opposed + * to dynamically creating new ones). This will in theory keep memory usage + * low and eliminate the need for reserving new memory whenever a new tile is + * needed. + * + * Default value: false. + */ + reuseTiles?: boolean; + + /** + * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. + */ + bounds?: LatLngBounds; + + /** + * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. + */ + [additionalKeys: string]: any; + } +} + +declare namespace L { + export interface TransformationStatic { + /** + * Creates a transformation object with the given coefficients. + */ + new(a: number, b: number, c: number, d: number): Transformation; + } + export var Transformation: TransformationStatic; + + export interface Transformation { + /** + * Returns a transformed point, optionally multiplied by the given scale. + * Only accepts real L.Point instances, not arrays. + */ + transform(point: Point, scale?: number): Point; + + /** + * Returns the reverse transformation of the given point, optionally divided + * by the given scale. Only accepts real L.Point instances, not arrays. + */ + untransform(point: Point, scale?: number): Point; + } +} + +declare namespace L { + + namespace Util { + + /** + * Merges the properties of the src object (or multiple objects) into dest object + * and returns the latter. Has an L.extend shortcut. + */ + export function extend(dest: any, ...sources: any[]): any; + + /** + * Returns a function which executes function fn with the given scope obj (so + * that this keyword refers to obj inside the function code). Has an L.bind shortcut. + */ + export function bind(fn: T, obj: any): T; + + /** + * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. + */ + export function stamp(obj: any): string; + + /** + * Returns a wrapper around the function fn that makes sure it's called not more + * often than a certain time interval time, but as fast as possible otherwise + * (for example, it is used for checking and requesting new tiles while dragging + * the map), optionally passing the scope (context) in which the function will + * be called. + */ + export function limitExecByInterval(fn: T, time: number, context?: any): T; + + /** + * Returns a function which always returns false. + */ + export function falseFn(): () => boolean; + + /** + * Returns the number num rounded to digits decimals. + */ + export function formatNum(num: number, digits: number): number; + + /** + * Trims and splits the string on whitespace and returns the array of parts. + */ + export function splitWords(str: string): string[]; + + /** + * Merges the given properties to the options of the obj object, returning the + * resulting options. See Class options. Has an L.setOptions shortcut. + */ + export function setOptions(obj: any, options: any): any; + + /** + * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} + * translates to '?a=foo&b=bar'. + */ + export function getParamString(obj: any): string; + + /** + * Simple templating facility, creates a string by applying the values of the + * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form + * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. + */ + export function template(str: string, data: any): string; + + /** + * Returns true if the given object is an array. + */ + export function isArray(obj: any): boolean; + + /** + * Trims the whitespace from both ends of the string and returns the result. + */ + export function trim(str: string): string; + + /** + * Data URI string containing a base64-encoded empty GIF image. Used as a hack + * to free memory from unused images on WebKit-powered mobile devices (by setting + * image src to this string). + */ + export var emptyImageUrl: string; + } +} + + +declare namespace L { + + export interface WMSOptions { + + /** + * (required) Comma-separated list of WMS layers to show. + * + * Default value: ''. + */ + layers?: string; + + /** + * Comma-separated list of WMS styles. + * + * Default value: 'image/jpeg'. + */ + styles?: string; + + /** + * WMS image format (use 'image/png' for layers with transparency). + * + * Default value: false. + */ + format?: string; + + /** + * If true, the WMS service will return images with transparency. + * + * Default value: '1.1.1'. + */ + transparent?: boolean; + + /** + * Version of the WMS service to use. + */ + version?: string; + + } +} + +/** + * Forces Leaflet to use the Canvas back-end (if available) for vector layers + * instead of SVG. This can increase performance considerably in some cases + * (e.g. many thousands of circle markers on the map). + */ +declare var L_PREFER_CANVAS: boolean; + +/** + * Forces Leaflet to not use touch events even if it detects them. + */ +declare var L_NO_TOUCH: boolean; + +/** + * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning + * (which may cause glitches in some rare environments) even if they're supported. + */ +declare var L_DISABLE_3D: boolean; + +declare module "leaflet" { + export = L; +} + +// vim: et ts=4 sw=4 diff --git a/meteor/meteor-tests.ts.tscparams b/meteor/meteor-tests.ts.tscparams index 2f5856b19..3195c46cd 100644 --- a/meteor/meteor-tests.ts.tscparams +++ b/meteor/meteor-tests.ts.tscparams @@ -1 +1 @@ ---noImplicitAny +--noImplicitAny diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 1f8a8e872..17ee6e0a9 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,6082 +1,6082 @@ -// Type definitions for three.js r73 -// Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon , Satoru Kimura -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module THREE { - export var REVISION: string; - - // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button - export enum MOUSE { LEFT, MIDDLE, RIGHT } - - // GL STATE CONSTANTS - export enum CullFace { } - export var CullFaceNone: CullFace; - export var CullFaceBack: CullFace; - export var CullFaceFront: CullFace; - export var CullFaceFrontBack: CullFace; - - export enum FrontFaceDirection { } - export var FrontFaceDirectionCW: FrontFaceDirection; - export var FrontFaceDirectionCCW: FrontFaceDirection; - - // Shadowing Type - export enum ShadowMapType { } - export var BasicShadowMap: ShadowMapType; - export var PCFShadowMap: ShadowMapType; - export var PCFSoftShadowMap: ShadowMapType; - - // MATERIAL CONSTANTS - - // side - export enum Side { } - export var FrontSide: Side; - export var BackSide: Side; - export var DoubleSide: Side; - - // shading - export enum Shading { } - export var NoShading: Shading; - export var FlatShading: Shading; - export var SmoothShading: Shading; - - // colors - export enum Colors { } - export var NoColors: Colors; - export var FaceColors: Colors; - export var VertexColors: Colors; - - // blending modes - export enum Blending { } - export var NoBlending: Blending; - export var NormalBlending: Blending; - export var AdditiveBlending: Blending; - export var SubtractiveBlending: Blending; - export var MultiplyBlending: Blending; - export var CustomBlending: Blending; - - // custom blending equations - // (numbers start from 100 not to clash with other - // mappings to OpenGL constants defined in Texture.js) - export enum BlendingEquation { } - export var AddEquation: BlendingEquation; - export var SubtractEquation: BlendingEquation; - export var ReverseSubtractEquation: BlendingEquation; - export var MinEquation: BlendingEquation; - export var MaxEquation: BlendingEquation; - - // custom blending destination factors - export enum BlendingDstFactor { } - export var ZeroFactor: BlendingDstFactor; - export var OneFactor: BlendingDstFactor; - export var SrcColorFactor: BlendingDstFactor; - export var OneMinusSrcColorFactor: BlendingDstFactor; - export var SrcAlphaFactor: BlendingDstFactor; - export var OneMinusSrcAlphaFactor: BlendingDstFactor; - export var DstAlphaFactor: BlendingDstFactor; - export var OneMinusDstAlphaFactor: BlendingDstFactor; - - // custom blending src factors - export enum BlendingSrcFactor { } - export var DstColorFactor: BlendingSrcFactor; - export var OneMinusDstColorFactor: BlendingSrcFactor; - export var SrcAlphaSaturateFactor: BlendingSrcFactor; - - // depth modes - export enum DepthModes { } - export var NeverDepth: DepthModes; - export var AlwaysDepth: DepthModes; - export var LessDepth: DepthModes; - export var LessEqualDepth: DepthModes; - export var EqualDepth: DepthModes; - export var GreaterEqualDepth: DepthModes; - export var GreaterDepth: DepthModes; - export var NotEqualDepth: DepthModes; - - // TEXTURE CONSTANTS - // Operations - export enum Combine { } - export var MultiplyOperation: Combine; - export var MixOperation: Combine; - export var AddOperation: Combine; - - // Mapping modes - export enum Mapping { } - export var UVMapping: Mapping; - export var CubeReflectionMapping: Mapping; - export var CubeRefractionMapping: Mapping; - export var EquirectangularReflectionMapping: Mapping; - export var EquirectangularRefractionMapping: Mapping; - export var SphericalReflectionMapping: Mapping; - - // Wrapping modes - export enum Wrapping { } - export var RepeatWrapping: Wrapping; - export var ClampToEdgeWrapping: Wrapping; - export var MirroredRepeatWrapping: Wrapping; - - // Filters - export enum TextureFilter { } - export var NearestFilter: TextureFilter; - export var NearestMipMapNearestFilter: TextureFilter; - export var NearestMipMapLinearFilter: TextureFilter; - export var LinearFilter: TextureFilter; - export var LinearMipMapNearestFilter: TextureFilter; - export var LinearMipMapLinearFilter: TextureFilter; - - // Data types - export enum TextureDataType { } - export var UnsignedByteType: TextureDataType; - export var ByteType: TextureDataType; - export var ShortType: TextureDataType; - export var UnsignedShortType: TextureDataType; - export var IntType: TextureDataType; - export var UnsignedIntType: TextureDataType; - export var FloatType: TextureDataType; - export var HalfFloatType: TextureDataType; - - // Pixel types - export enum PixelType { } - export var UnsignedShort4444Type: PixelType; - export var UnsignedShort5551Type: PixelType; - export var UnsignedShort565Type: PixelType; - - // Pixel formats - export enum PixelFormat { } - export var AlphaFormat: PixelFormat; - export var RGBFormat: PixelFormat; - export var RGBAFormat: PixelFormat; - export var LuminanceFormat: PixelFormat; - export var LuminanceAlphaFormat: PixelFormat; - export var RGBEFormat: PixelFormat; - - // Compressed texture formats - // DDS / ST3C Compressed texture formats - export enum CompressedPixelFormat { } - export var RGB_S3TC_DXT1_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT1_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT3_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT5_Format: CompressedPixelFormat; - - // PVRTC compressed texture formats - export var RGB_PVRTC_4BPPV1_Format: CompressedPixelFormat; - export var RGB_PVRTC_2BPPV1_Format: CompressedPixelFormat; - export var RGBA_PVRTC_4BPPV1_Format: CompressedPixelFormat; - export var RGBA_PVRTC_2BPPV1_Format: CompressedPixelFormat; - - // Loop styles for AnimationAction - export enum AnimationActionLoopStyles { } - export var LoopOnce: AnimationActionLoopStyles; - export var LoopRepeat: AnimationActionLoopStyles; - export var LoopPingPong: AnimationActionLoopStyles; - - // log handlers - export function warn(message?: any, ...optionalParams: any[]): void; - export function error(message?: any, ...optionalParams: any[]): void; - export function log(message?: any, ...optionalParams: any[]): void; - - // Animation //////////////////////////////////////////////////////////////////////////////////////// - export class AnimationAction { - constructor(clip: AnimationClip, startTime?: number, timeScale?: number, weight?: number, loop?: boolean); - - clip: AnimationClip - localRoot: Mesh; - startTime: number; - timeScale: number; - weight: number; - loop: AnimationActionLoopStyles; - loopCount: number; - enabled: boolean; - actionTime: number; - clipTime: number; - propertyBindings: PropertyBinding[]; - - setLocalRoot( localRoot: Mesh ): AnimationAction; - updateTime( clipDeltaTime: number ): number; - syncWith( action: AnimationAction ): AnimationAction; - warpToDuration( duration: number ): AnimationAction; - init( time: number ): AnimationAction; - update( clipDeltaTime: number ): any[]; - getTimeScaleAt( time: number ): number; - getWeightAt( time: number ): number; - } - - export class AnimationClip { - constructor( name: string, duration?: number, tracks?: KeyframeTrack[] ); - - name: string; - tracks: KeyframeTrack[]; - duration: number; - results: any[]; - - getAt(clipTime: number): any[]; - trim(): AnimationClip; - optimize(): AnimationClip; - - static CreateFromMorphTargetSequence( name: string, morphTargetSequence: MorphTarget[], fps: number ): AnimationClip; - findByName( clipArray: AnimationClip, name: string ): AnimationClip; - static CreateClipsFromMorphTargetSequences( morphTargets: MorphTarget[], fps: number ): AnimationClip[]; - parse( json: any ): AnimationClip; - parseAnimation( animation: any, bones: Bone[], nodeName: string ): AnimationClip; - } - - export class AnimationMixer { - constructor( root: any ); - - root: any; - time: number; - timeScale: number; - actions: AnimationAction; - propertyBindingMap: any; - - addAction( action: AnimationAction ): void; - removeAllActions(): AnimationMixer; - removeAction( action: AnimationAction ): AnimationMixer; - findActionByName( name: string ): AnimationAction; - play( action: AnimationAction, optionalFadeInDuration?: number ): AnimationMixer; - fadeOut( action: AnimationAction, duration: number ): AnimationMixer; - fadeIn( action: AnimationAction, duration: number ): AnimationMixer; - warp( action: AnimationAction, startTimeScale: NumberKeyframeTrack, endTimeScale: NumberKeyframeTrack, duration: number ): AnimationMixer; - crossFade( fadeOutAction: AnimationAction, fadeInAction: AnimationAction, duration: number, warp: boolean ): AnimationMixer; - update( deltaTime: number ): AnimationMixer; - } - - export var AnimationUtils: { - getEqualsFunc( exemplarValue: any ): boolean; - clone(exemplarValue: T): T; - lerp( a: any, b: any, alpha: number, interTrack: boolean ): any; - lerp_object( a: any, b: any, alpha: number ): any; - slerp_object( a: any, b: any, alpha: number ): any; - lerp_number( a: any, b: any, alpha: number ): any; - lerp_boolean( a: any, b: any, alpha: number ): any; - lerp_boolean_immediate( a: any, b: any, alpha: number ): any; - lerp_string( a: any, b: any, alpha: number ): any; - lerp_string_immediate( a: any, b: any, alpha: number ): any; - getLerpFunc( exemplarValue: any, interTrack: boolean ): Function; - }; - - export class KeyframeTrack { - constructor(name: string, keys: any[]); - - name: string; - keys: any[]; - lastIndex: number; - - getAt( time: number ): any; - shift( timeOffset: number ): KeyframeTrack; - scale( timeScale: number ): KeyframeTrack; - trim( startTime: number, endTime: number ): KeyframeTrack; - validate(): KeyframeTrack; - optimize(): KeyframeTrack; - - keyComparator(key0: KeyframeTrack, key1: KeyframeTrack): number; - parse( json: any ): KeyframeTrack; - GetTrackTypeForTypeName( typeName: string ): any; - } - - export class PropertyBinding { - constructor( rootNode: any, trackName: string ); - - rootNode: any; - trackName: string; - referenceCount: number; - originalValue: any; - directoryName: string; - nodeName: string; - objectName: string; - objectIndex: number; - propertyName: string; - propertyIndex: number; - node: any; - cumulativeValue: number; - cumulativeWeight: number; - - reset(): void; - accumulate( value: any, weight: number ): void; - unbind(): void; - bind(): void; - apply(): void; - parseTrackName( trackName: string ): any; - findNode( root: any, nodeName: string ): any; - } - - export class BooleanKeyframeTrack extends KeyframeTrack { - constructor(name: string, keys: any[]); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): BooleanKeyframeTrack; - parse( json: any ): BooleanKeyframeTrack; - } - - export class NumberKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): NumberKeyframeTrack; - parse( json: any ): NumberKeyframeTrack; - } - - export class QuaternionKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): QuaternionKeyframeTrack; - parse( json: any ): QuaternionKeyframeTrack; - } - - export class StringKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): StringKeyframeTrack; - parse( json: any ): StringKeyframeTrack; - } - - export class VectorKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): VectorKeyframeTrack; - parse( json: any ): VectorKeyframeTrack; - } - - // Cameras //////////////////////////////////////////////////////////////////////////////////////// - - /** - * Abstract base class for cameras. This class should always be inherited when you build a new camera. - */ - export class Camera extends Object3D { - /** - * This constructor sets following properties to the correct type: matrixWorldInverse, projectionMatrix and projectionMatrixInverse. - */ - constructor(); - - /** - * This is the inverse of matrixWorld. MatrixWorld contains the Matrix which has the world transform of the Camera. - */ - matrixWorldInverse: Matrix4; - - /** - * This is the matrix which contains the projection. - */ - projectionMatrix: Matrix4; - - getWorldDirection(optionalTarget?: Vector3): Vector3; - - /** - * This make the camera look at the vector position in local space. - * @param vector point to look at - */ - lookAt(vector: Vector3): void; - - clone(): Camera; - copy(camera?: Camera): Camera; - } - - export class CubeCamera extends Object3D { - constructor( near?: number, far?: number, cubeResolution?: number); - - renderTarget: WebGLRenderTargetCube; - - updateCubeMap( renderer: Renderer, scene: Scene ): void; - - } - - /** - * Camera with orthographic projection - * - * @example - * var camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); - * scene.add( camera ); - * - * @see src/cameras/OrthographicCamera.js - */ - export class OrthographicCamera extends Camera { - /** - * @param left Camera frustum left plane. - * @param right Camera frustum right plane. - * @param top Camera frustum top plane. - * @param bottom Camera frustum bottom plane. - * @param near Camera frustum near plane. - * @param far Camera frustum far plane. - */ - constructor(left: number, right: number, top: number, bottom: number, near?: number, far?: number); - - zoom: number; - - /** - * Camera frustum left plane. - */ - left: number; - - /** - * Camera frustum right plane. - */ - right: number; - - /** - * Camera frustum top plane. - */ - top: number; - - /** - * Camera frustum bottom plane. - */ - bottom: number; - - /** - * Camera frustum near plane. - */ - near: number; - - /** - * Camera frustum far plane. - */ - far: number; - - /** - * Updates the camera projection matrix. Must be called after change of parameters. - */ - updateProjectionMatrix(): void; - clone(): OrthographicCamera; - copy( source: OrthographicCamera ): OrthographicCamera; - toJSON( meta?: any ): any; - } - - /** - * Camera with perspective projection. - * - * # example - * var camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); - * scene.add( camera ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/cameras/PerspectiveCamera.js - */ - export class PerspectiveCamera extends Camera { - /** - * @param fov Camera frustum vertical field of view. Default value is 50. - * @param aspect Camera frustum aspect ratio. Default value is 1. - * @param near Camera frustum near plane. Default value is 0.1. - * @param far Camera frustum far plane. Default value is 2000. - */ - constructor(fov?: number, aspect?: number, near?: number, far?: number); - - zoom: number; - - /** - * Camera frustum vertical field of view, from bottom to top of view, in degrees. - */ - fov: number; - - /** - * Camera frustum aspect ratio, window width divided by window height. - */ - aspect: number; - - /** - * Camera frustum near plane. - */ - near: number; - - /** - * Camera frustum far plane. - */ - far: number; - - /** - * Uses focal length (in mm) to estimate and set FOV 35mm (fullframe) camera is used if frame size is not specified. - * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html - * @param focalLength focal length - * @param frameHeight frame size. Default value is 24. - */ - setLens(focalLength: number, frameHeight?: number): void; - - /** - * Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups. - * For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this: - * - * +---+---+---+ - * | A | B | C | - * +---+---+---+ - * | D | E | F | - * +---+---+---+ - * - * then for each monitor you would call it like this: - * - * var w = 1920; - * var h = 1080; - * var fullWidth = w * 3; - * var fullHeight = h * 2; - * - * // A - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); - * // B - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); - * // C - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); - * // D - * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); - * // E - * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); - * // F - * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); Note there is no reason monitors have to be the same size or in a grid. - * - * @param fullWidth full width of multiview setup - * @param fullHeight full height of multiview setup - * @param x horizontal offset of subcamera - * @param y vertical offset of subcamera - * @param width width of subcamera - * @param height height of subcamera - */ - setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void; - - /** - * Updates the camera projection matrix. Must be called after change of parameters. - */ - updateProjectionMatrix(): void; - clone(): PerspectiveCamera; - copy( source: PerspectiveCamera ): PerspectiveCamera; - toJSON( meta?: any ): any; - } - - // Core /////////////////////////////////////////////////////////////////////////////////////////////// - - /** - * @see src/core/BufferAttribute.js - */ - export class BufferAttribute { - constructor(array: ArrayLike, itemSize: number); // array parameter should be TypedArray. - - uuid: string; - array: ArrayLike; - itemSize: number; - dynamic: boolean; - updateRange: {offset:number, count:number}; - version: number; - - needsUpdate: boolean; - /** Deprecated, use count instead */ - length: number; - count: number; - - setDynamic(dynamic: boolean): BufferAttribute; - clone(): BufferAttribute; - copy(source: BufferAttribute): BufferAttribute; - copyAt(index1: number, attribute: BufferAttribute, index2: number): BufferAttribute; - copyArray(array: ArrayLike): BufferAttribute; - copyColorsArray(colors: {r:number, g:number, b:number}[]): BufferAttribute; - copyIndicesArray(indices: {a:number, b:number, c:number}[]): BufferAttribute; - copyVector2sArray(vectors: {x:number, y:number}[]): BufferAttribute; - copyVector3sArray(vectors: {x:number, y:number, z:number}[]): BufferAttribute; - copyVector4sArray(vectors: {x:number, y:number, z:number, w:number}[]): BufferAttribute; - set(value: ArrayLike, offset?: number): BufferAttribute; - getX(index: number): number; - setX(index: number, x: number): BufferAttribute; - getY(index: number): number; - setY(index: number, y: number): BufferAttribute; - getZ(index: number): number; - setZ(index: number, z: number): BufferAttribute; - getW(index: number): number; - setW(index: number, z: number): BufferAttribute; - setXY(index: number, x: number, y: number): BufferAttribute; - setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; - setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; - clone(): BufferAttribute; - } - - // deprecated (are these actually deprecated?) - export class Int8Attribute extends BufferAttribute{ - constructor(array: any, itemSize: number); - } - - // deprecated - export class Uint8Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Uint8ClampedAttribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Int16Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Uint16Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Int32Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Uint32Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Float32Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - // deprecated - export class Float64Attribute extends BufferAttribute { - constructor(array: any, itemSize: number); - } - - /** - * This is a superefficent class for geometries because it saves all data in buffers. - * It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the nessecary buffer calculations. - * It is mainly interesting when working with static objects. - * - * @see src/core/BufferGeometry.js - */ - export class BufferGeometry { - /** - * This creates a new BufferGeometry. It also sets several properties to an default value. - */ - constructor(); - - static MaxIndex: number; - - /** - * Unique number of this buffergeometry instance - */ - id: number; - uuid: string; - name: string; - type: string; - index: BufferAttribute; - attributes: BufferAttribute|InterleavedBufferAttribute[]; - morphAttributes: any; - groups: {start: number, count: number, materialIndex?: number}[]; - boundingBox: Box3; - boundingSphere: BoundingSphere; - drawRange: { start: number, count: number }; - - /** Deprecated. */ - addIndex( index: BufferAttribute ): void; - - getIndex(): BufferAttribute; - setIndex( index: BufferAttribute ): void; - - /** Deprecated. This overloaded method is deprecated. */ - addAttribute(name: string, array: any, itemSize: number): any; - addAttribute(name: string, attribute: BufferAttribute|InterleavedBufferAttribute): void; - getAttribute(name: string): BufferAttribute|InterleavedBufferAttribute; - removeAttribute(name: string): void; - - /** Deprecated. */ - drawcalls(): any; - /** Deprecated. */ - offsets(): any; - - /** Deprecated. Use addGroup */ - addDrawCall(start: number, count: number, index?: number): void; - /** Deprecated. */ - clearDrawCalls(): void; - addGroup(start: number, count: number, materialIndex?: number): void; - clearGroups(): void; - - setDrawRange(start: number, count: number): void; - - /** - * Bakes matrix transform directly into vertex coordinates. - */ - applyMatrix(matrix: Matrix4): void; - - rotateX(angle: number): BufferGeometry; - rotateY(angle: number): BufferGeometry; - rotateZ(angle: number): BufferGeometry; - translate(x: number, y: number, z: number): BufferGeometry; - scale(x: number, y: number, z: number): BufferGeometry; - lookAt(v: Vector3): void; - - center(): Vector3; - - setFromObject(object: Object3D) : void; - updateFromObject(object: Object3D) : void; - - fromGeometry(geometry: Geometry, settings?: any): BufferGeometry; - - fromDirectGeometry( geometry: DirectGeometry ): BufferGeometry; - - /** - * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. - * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. - */ - computeBoundingBox(): void; - - /** - * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. - * Bounding spheres aren't' computed by default. They need to be explicitly computed, otherwise they are null. - */ - computeBoundingSphere(): void; - - // deprecated - computeFaceNormals(): void; - - /** - * Computes vertex normals by averaging face normals. - */ - computeVertexNormals(): void; - - computeOffsets(size: number): void; - merge(geometry: BufferGeometry, offset: number): BufferGeometry; - normalizeNormals(): void; - toJSON(): any; - clone(): BufferGeometry; - copy(source: BufferGeometry): BufferGeometry; - - /** - * Disposes the object from memory. - * You need to call this when you want the bufferGeometry removed while the application is running. - */ - dispose(): void; - - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - } - - export class Channels { - constructor(); - - mask: number; - - set( channel: number ): void; - enable( channel: number ): void; - toggle( channel: number ): void; - disable( channel: number ): void; - } - - /** - * Object for keeping track of time. - * - * @see src/core/Clock.js - */ - export class Clock { - /** - * @param autoStart Automatically start the clock. - */ - constructor(autoStart?: boolean); - - /** - * If set, starts the clock automatically when the first update is called. - */ - autoStart: boolean; - - /** - * When the clock is running, It holds the starttime of the clock. - * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. - */ - startTime: number; - - /** - * When the clock is running, It holds the previous time from a update. - * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. - */ - oldTime: number; - - /** - * When the clock is running, It holds the time elapsed between the start of the clock to the previous update. - * This parameter is in seconds of three decimal places. - */ - elapsedTime: number; - - /** - * This property keeps track whether the clock is running or not. - */ - running: boolean; - - /** - * Starts clock. - */ - start(): void; - - /** - * Stops clock. - */ - stop(): void; - - /** - * Get the seconds passed since the clock started. - */ - getElapsedTime(): number; - - /** - * Get the seconds passed since the last call to this method. - */ - getDelta(): number; - } - - /** - * @see src/core/DirectGeometry.js - */ - export class DirectGeometry { - constructor(); - - id: number; - uuid: string; - name: string; - type: string; - indices: number[]; - vertices: Vector3[]; - normals: Vector3[]; - colors: Color[]; - uvs: Vector2[]; - uvs2: Vector2[]; - groups: {start: number, materialIndex: number}[]; - morphTargets: MorphTarget[]; - skinWeights: number[]; - skinIndices: number[]; - boundingBox: Box3; - boundingSphere: BoundingSphere; - verticesNeedUpdate: boolean; - normalsNeedUpdate: boolean; - colorsNeedUpdate: boolean; - uvsNeedUpdate: boolean; - groupsNeedUpdate: boolean; - - computeBoundingBox(): void; - computeBoundingSphere(): void; - computeGroups(geometry: Geometry): void; - fromGeometry(geometry: Geometry): DirectGeometry; - dispose(): void; - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - } - - /** - * JavaScript events for custom objects - * - * # Example - * var Car = function () { - * - * EventDispatcher.call( this ); - * this.start = function () { - * - * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } ); - * - * }; - * - * }; - * - * var car = new Car(); - * car.addEventListener( 'start', function ( event ) { - * - * alert( event.message ); - * - * } ); - * car.start(); - * - * @source src/core/EventDispatcher.js - */ - export class EventDispatcher { - /** - * Creates eventDispatcher object. It needs to be call with '.call' to add the functionality to an object. - */ - constructor(); - - /** - * Adds a listener to an event type. - * @param type The type of the listener that gets removed. - * @param listener The listener function that gets removed. - */ - addEventListener(type: string, listener: (event: any) => void ): void; - - /** - * Adds a listener to an event type. - * @param type The type of the listener that gets removed. - * @param listener The listener function that gets removed. - */ - hasEventListener(type: string, listener: (event: any) => void): void; - - /** - * Removes a listener from an event type. - * @param type The type of the listener that gets removed. - * @param listener The listener function that gets removed. - */ - removeEventListener(type: string, listener: (event: any) => void): void; - - /** - * Fire an event type. - * @param type The type of event that gets fired. - */ - dispatchEvent(event: { type: string; target: any; }): void; - } - - /** - * Triangle face. - * - * # Example - * var normal = new THREE.Vector3( 0, 1, 0 ); - * var color = new THREE.Color( 0xffaa00 ); - * var face = new THREE.Face3( 0, 1, 2, normal, color, 0 ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/core/Face3.js - */ - export class Face3 { - /** - * @param a Vertex A index. - * @param b Vertex B index. - * @param c Vertex C index. - * @param normal Face normal or array of vertex normals. - * @param color Face color or array of vertex colors. - * @param materialIndex Material index. - */ - constructor(a: number, b: number, c: number, normal?: Vector3, color?: Color, materialIndex?: number); - constructor(a: number, b: number, c: number, normal?: Vector3, vertexColors?: Color[], materialIndex?: number); - constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], color?: Color, materialIndex?: number); - constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], vertexColors?: Color[], materialIndex?: number); - - /** - * Vertex A index. - */ - a: number; - - /** - * Vertex B index. - */ - b: number; - - /** - * Vertex C index. - */ - c: number; - - /** - * Face normal. - */ - normal: Vector3; - - /** - * Array of 4 vertex normals. - */ - vertexNormals: Vector3[]; - - /** - * Face color. - */ - color: Color; - - /** - * Array of 4 vertex normals. - */ - vertexColors: Color[]; - - /** - * Array of 4 vertex tangets. - */ - vertexTangents: number[]; - - /** - * Material index (points to {@link Geometry.materials}). - */ - materialIndex: number; - - clone(): Face3; - } - - export interface MorphTarget { - name: string; - vertices: Vector3[]; - } - - export interface MorphColor { - name: string; - colors: Color[]; - } - - export interface MorphNormals { - name: string; - normals: Vector3[]; - } - - export interface BoundingSphere { - radius: number; - } - - /** - * Base class for geometries - * - * # Example - * var geometry = new THREE.Geometry(); - * geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ) ); - * geometry.vertices.push( new THREE.Vector3( -10, -10, 0 ) ); - * geometry.vertices.push( new THREE.Vector3( 10, -10, 0 ) ); - * geometry.faces.push( new THREE.Face3( 0, 1, 2 ) ); - * geometry.computeBoundingSphere(); - * - * @see https://github.com/mrdoob/three.js/blob/master/src/core/Geometry.js - */ - export class Geometry { - constructor(); - - /** - * Unique number of this geometry instance - */ - id: number; - - uuid: string; - - /** - * Name for this geometry. Default is an empty string. - */ - name: string; - - type: string; - - /** - * The array of vertices hold every position of points of the model. - * To signal an update in this array, Geometry.verticesNeedUpdate needs to be set to true. - */ - vertices: Vector3[]; - - /** - * Array of vertex colors, matching number and order of vertices. - * Used in ParticleSystem, Line and Ribbon. - * Meshes use per-face-use-of-vertex colors embedded directly in faces. - * To signal an update in this array, Geometry.colorsNeedUpdate needs to be set to true. - */ - colors: Color[]; - - /** - * Array of triangles or/and quads. - * The array of faces describe how each vertex in the model is connected with each other. - * To signal an update in this array, Geometry.elementsNeedUpdate needs to be set to true. - */ - faces: Face3[]; - - /** - * Array of face UV layers. - * Each UV layer is an array of UV matching order and number of vertices in faces. - * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. - */ - faceVertexUvs: Vector2[][][]; - - /** - * Array of morph targets. Each morph target is a Javascript object: - * - * { name: "targetName", vertices: [ new THREE.Vector3(), ... ] } - * - * Morph vertices match number and order of primary vertices. - */ - morphTargets: MorphTarget[]; - - /** - * Array of morph normals. Morph normals have similar structure as morph targets, each normal set is a Javascript object: - * - * morphNormal = { name: "NormalName", normals: [ new THREE.Vector3(), ... ] } - */ - morphNormals: MorphNormals[]; - - /** - * Array of skinning weights, matching number and order of vertices. - */ - skinWeights: number[]; - - /** - * Array of skinning indices, matching number and order of vertices. - */ - skinIndices: number[]; - - /** - * - */ - lineDistances: number[]; - - /** - * Bounding box. - */ - boundingBox: Box3; - - /** - * Bounding sphere. - */ - boundingSphere: BoundingSphere; - - /** - * Set to true if the vertices array has been updated. - */ - verticesNeedUpdate: boolean; - - /** - * Set to true if the faces array has been updated. - */ - elementsNeedUpdate: boolean; - - /** - * Set to true if the uvs array has been updated. - */ - uvsNeedUpdate: boolean; - - /** - * Set to true if the normals array has been updated. - */ - normalsNeedUpdate: boolean; - - /** - * Set to true if the colors array has been updated. - */ - colorsNeedUpdate: boolean; - - /** - * Set to true if the linedistances array has been updated. - */ - lineDistancesNeedUpdate: boolean; - - /** - * - */ - groupsNeedUpdate: boolean; - - /** - * Bakes matrix transform directly into vertex coordinates. - */ - applyMatrix(matrix: Matrix4): void; - - rotateX(angle: number): Geometry; - rotateY(angle: number): Geometry; - rotateZ(angle: number): Geometry; - - translate(x: number, y: number, z: number): Geometry; - scale(x: number, y: number, z: number): Geometry; - lookAt( vector: Vector3 ): void; - - - fromBufferGeometry(geometry: BufferGeometry): Geometry; - - /** - * - */ - center(): Vector3; - - normalize(): Geometry; - - /** - * Computes face normals. - */ - computeFaceNormals(): void; - - /** - * Computes vertex normals by averaging face normals. - * Face normals must be existing / computed beforehand. - */ - computeVertexNormals(areaWeighted?: boolean): void; - - /** - * Computes morph normals. - */ - computeMorphNormals(): void; - - computeLineDistances(): void; - - /** - * Computes bounding box of the geometry, updating {@link Geometry.boundingBox} attribute. - */ - computeBoundingBox(): void; - - /** - * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. - * Neither bounding boxes or bounding spheres are computed by default. They need to be explicitly computed, otherwise they are null. - */ - computeBoundingSphere(): void; - - merge( geometry: Geometry, matrix: Matrix, materialIndexOffset?: number): void; - - mergeMesh( mesh: Mesh ): void; - - /** - * Checks for duplicate vertices using hashmap. - * Duplicated vertices are removed and faces' vertices are updated. - */ - mergeVertices(): number; - - sortFacesByMaterialIndex(): void; - - toJSON(): any; - - /** - * Creates a new clone of the Geometry. - */ - clone(): Geometry; - - copy(source: Geometry): Geometry; - - /** - * Removes The object from memory. - * Don't forget to call this method when you remove an geometry because it can cuase meomory leaks. - */ - dispose(): void; - - - //These properties do not exist in a normal Geometry class, but if you use the instance that was passed by JSONLoader, it will be added. - bones: Bone[]; - animation: AnimationClip; - animations: AnimationClip[]; - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - } - - /** - * @see src/core/InstancedBufferAttribute.js - */ - export class InstancedBufferAttribute extends BufferAttribute { - constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); - meshPerAttribute: number; - - clone(): InstancedBufferAttribute; - copy(source: InstancedBufferAttribute): InstancedBufferAttribute; - } - - /** - * @see src/core/InstancedBufferGeometry.js - */ - export class InstancedBufferGeometry extends BufferGeometry { - constructor(); - groups: {start:number, count:number, instances:number}[]; - addGroup(start: number, count: number, instances: number): void; - - clone(): InstancedBufferGeometry; - copy(source: InstancedBufferGeometry): InstancedBufferGeometry; - } - - /** - * @see src/core/InstancedInterleavedBuffer.js - */ - export class InstancedInterleavedBuffer extends InterleavedBuffer { - constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); - meshPerAttribute: number; - - clone(): InstancedInterleavedBuffer; - copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; - } - - /** - * @see src/core/InterleavedBuffer.js - */ - export class InterleavedBuffer { - constructor(array: ArrayLike, stride: number); - array: ArrayLike; - stride: number; - dynamic: boolean; - updateRange: {offset:number, count:number}; - version: number; - length: number; - count: number; - needsUpdate: boolean; - - setDynamic(dynamic: boolean): InterleavedBuffer; - clone(): InterleavedBuffer; - copy(source: InterleavedBuffer): InterleavedBuffer; - copyAt(index1: number, attribute: InterleavedBufferAttribute, index2: number): InterleavedBuffer; - set(value: ArrayLike, index: number): InterleavedBuffer; - clone(): InterleavedBuffer; - } - - /** - * @see src/core/InterleavedBufferAttribute.js - */ - export class InterleavedBufferAttribute { - constructor(interleavedBuffer: InterleavedBuffer, itemSize: number, offset: number); - - uuid: string; - data: InterleavedBuffer; - itemSize: number; - offset: number; - /** Deprecated, use count instead */ - length: number; - count: number; - - getX(index: number): number; - setX(index: number, x: number): InterleavedBufferAttribute; - getY(index: number): number; - setY(index: number, y: number): InterleavedBufferAttribute; - getZ(index: number): number; - setZ(index: number, z: number): InterleavedBufferAttribute; - getW(index: number): number; - setW(index: number, z: number): InterleavedBufferAttribute; - setXY(index: number, x: number, y: number): InterleavedBufferAttribute; - setXYZ(index: number, x: number, y: number, z: number): InterleavedBufferAttribute; - setXYZW(index: number, x: number, y: number, z: number, w: number): InterleavedBufferAttribute; - } - - /** - * Base class for scene graph objects - */ - export class Object3D { - constructor(); - - /** - * Unique number of this object instance. - */ - id: number; - - /** - * - */ - uuid: string; - - /** - * Optional name of the object (doesn't need to be unique). - */ - name: string; - - type: string; - - /** - * Object's parent in the scene graph. - */ - parent: Object3D; - - channels: Channels; - - /** - * Array with object's children. - */ - children: Object3D[]; - - /** - * Up direction. - */ - up: Vector3; - - /** - * Object's local position. - */ - position: Vector3; - - /** - * Object's local rotation (Euler angles), in radians. - */ - rotation: Euler; - - /** - * Global rotation. - */ - quaternion: Quaternion; - - /** - * Object's local scale. - */ - scale: Vector3; - - modelViewMatrix: Matrix4; - - normalMatrix: Matrix3; - - /** - * When this is set, then the rotationMatrix gets calculated every frame. - */ - rotationAutoUpdate: boolean; - - /** - * Local transform. - */ - matrix: Matrix4; - - /** - * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. - */ - matrixWorld: Matrix4; - - /** - * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. - */ - matrixAutoUpdate: boolean; - - /** - * When this is set, it calculates the matrixWorld in that frame and resets this property to false. - */ - matrixWorldNeedsUpdate: boolean; - - /** - * Object gets rendered if true. - */ - visible: boolean; - - /** - * Gets rendered into shadow map. - */ - castShadow: boolean; - - /** - * Material gets baked in shadow receiving. - */ - receiveShadow: boolean; - - /** - * When this is set, it checks every frame if the object is in the frustum of the camera. Otherwise the object gets drawn every frame even if it isn't visible. - */ - frustumCulled: boolean; - - renderOrder: number; - - /** - * An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned. - */ - userData: any; - - /** - * - */ - static DefaultUp: Vector3; - static DefaultMatrixAutoUpdate: Vector3; - - /** - * This updates the position, rotation and scale with the matrix. - */ - applyMatrix(matrix: Matrix4): void; - - /** - * - */ - setRotationFromAxisAngle(axis: Vector3, angle: number): void; - - /** - * - */ - setRotationFromEuler(euler: Euler ): void; - - /** - * - */ - setRotationFromMatrix(m: Matrix4): void; - - /** - * - */ - setRotationFromQuaternion( q: Quaternion ): void; - - /** - * Rotate an object along an axis in object space. The axis is assumed to be normalized. - * @param axis A normalized vector in object space. - * @param angle The angle in radians. - */ - rotateOnAxis(axis: Vector3, angle: number): Object3D; - - /** - * - * @param angle - */ - rotateX(angle: number): Object3D; - - /** - * - * @param angle - */ - rotateY(angle: number): Object3D; - - /** - * - * @param angle - */ - rotateZ(angle: number): Object3D; - - /** - * @param axis A normalized vector in object space. - * @param distance The distance to translate. - */ - translateOnAxis(axis: Vector3, distance: number): Object3D; - - /** - * - * @param distance - * @param axis - */ - translate( distance: number, axis: Vector3 ): Object3D; - - /** - * Translates object along x axis by distance. - * @param distance Distance. - */ - translateX(distance: number): Object3D; - - /** - * Translates object along y axis by distance. - * @param distance Distance. - */ - translateY(distance: number): Object3D; - - /** - * Translates object along z axis by distance. - * @param distance Distance. - */ - translateZ(distance: number): Object3D; - - /** - * Updates the vector from local space to world space. - * @param vector A local vector. - */ - localToWorld(vector: Vector3): Vector3; - - /** - * Updates the vector from world space to local space. - * @param vector A world vector. - */ - worldToLocal(vector: Vector3): Vector3; - - /** - * Rotates object to face point in space. - * @param vector A world vector to look at. - */ - lookAt(vector: Vector3): void; - - /** - * Adds object as child of this object. - */ - add(object: Object3D): void; - - /** - * Removes object as child of this object. - */ - remove(object: Object3D): void; - - /* deprecated */ - getChildByName( name: string ): Object3D; - - /** - * Searches through the object's children and returns the first with a matching id, optionally recursive. - * @param id Unique number of the object instance - */ - getObjectById(id: number): Object3D; - - /** - * Searches through the object's children and returns the first with a matching name, optionally recursive. - * @param name String to match to the children's Object3d.name property. - */ - getObjectByName(name: string): Object3D; - - getObjectByProperty( name: string, value: string ): Object3D; - - getWorldPosition(optionalTarget?: Vector3): Vector3; - getWorldQuaternion(optionalTarget?: Quaternion): Quaternion; - getWorldRotation(optionalTarget?: Euler): Euler; - getWorldScale(optionalTarget?: Vector3): Vector3; - getWorldDirection(optionalTarget?: Vector3): Vector3; - - raycast(raycaster: Raycaster, intersects: any): void; - - traverse(callback: (object: Object3D) => any): void; - - traverseVisible(callback: (object: Object3D) => any): void; - - traverseAncestors(callback: (object: Object3D) => any): void; - - /** - * Updates local transform. - */ - updateMatrix(): void; - - /** - * Updates global transform of the object and its children. - */ - updateMatrixWorld(force: boolean): void; - - toJSON(meta?: any): any; - - clone(recursive?: boolean): Object3D; - - /** - * - * @param object - * @param recursive - */ - copy(source: Object3D, recursive?: boolean): Object3D; - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - - } - - export interface Intersection { - distance: number; - point: Vector3; - face: Face3; - object: Object3D; - } - - export interface RaycasterParameters { - Mesh?: any; - Line?: any; - LOD?: any; - Points?: any; - Sprite?: any; - } - - export class Raycaster { - constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number); - - ray: Ray; - near: number; - far: number; - params: RaycasterParameters; - precision: number; - linePrecision: number; - set(origin: Vector3, direction: Vector3): void; - setFromCamera(coords: { x: number; y: number;}, camera: Camera ): void; - intersectObject(object: Object3D, recursive?: boolean): Intersection[]; - intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; - } - - // Lights ////////////////////////////////////////////////////////////////////////////////// - - /** - * Abstract base class for lights. - */ - export class Light extends Object3D { - constructor(hex?: number|string); - - color: Color; - receiveShadow: boolean; - - shadowCameraFov: number; - shadowCameraLeft: number; - shadowCameraRight: number; - shadowCameraTop: number; - shadowCameraBottom: number; - shadowCameraNear: number; - shadowCameraFar: number; - shadowBias: number; - shadowDarkness: number; - shadowMapWidth: number; - shadowMapHeight: number; - - clone(recursive?: boolean): Light; - copy( source: Light ): Light; - toJSON( meta: any ): any; - } - - export class LightShadow { - constructor(camera: Camera); - - camera: Camera; - bias: number; - darkness: number; - mapSize: Vector2; - map: RenderTarget; - matrix: Matrix4; - - copy(source: LightShadow): void; - clone(): LightShadow; - } - - /** - * This light's color gets applied to all the objects in the scene globally. - * - * # example - * var light = new THREE.AmbientLight( 0x404040 ); // soft white light - * scene.add( light ); - * - * @source https://github.com/mrdoob/three.js/blob/master/src/lights/AmbientLight.js - */ - export class AmbientLight extends Light { - /** - * This creates a Ambientlight with a color. - * @param hex Numeric value of the RGB component of the color. - */ - constructor(hex?: number|string); - - clone(recursive?: boolean): AmbientLight; - copy(source: AmbientLight): AmbientLight; - } - - /** - * Affects objects using MeshLambertMaterial or MeshPhongMaterial. - * - * @example - * // White directional light at half intensity shining from the top. - * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); - * directionalLight.position.set( 0, 1, 0 ); - * scene.add( directionalLight ); - * - * @see src/lights/DirectionalLight.js - */ - export class DirectionalLight extends Light { - - constructor(hex?: number|string, intensity?: number); - - /** - * Target used for shadow camera orientation. - */ - target: Object3D; - - /** - * Light's intensity. - * Default — 1.0. - */ - intensity: number; - - shadow: LightShadow; - - clone(recursive?: boolean): DirectionalLight; - copy(source: DirectionalLight): DirectionalLight; - } - - export class HemisphereLight extends Light { - constructor(skyColorHex?: number|string, groundColorHex?: number|string, intensity?: number); - - groundColor: Color; - intensity: number; - - clone(recursive?: boolean): HemisphereLight; - copy(source: HemisphereLight): HemisphereLight; - } - - /** - * Affects objects using {@link MeshLambertMaterial} or {@link MeshPhongMaterial}. - * - * @example - * var light = new THREE.PointLight( 0xff0000, 1, 100 ); - * light.position.set( 50, 50, 50 ); - * scene.add( light ); - */ - export class PointLight extends Light { - constructor(hex?: number|string, intensity?: number, distance?: number, decay?: number); - - /* - * Light's intensity. - * Default - 1.0. - */ - intensity: number; - - /** - * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. - * Default — 0.0. - */ - distance: number; - - decay: number; - - shadow: LightShadow; - - clone(recursive?: boolean): PointLight; - copy(source: PointLight): PointLight; - } - - /** - * A point light that can cast shadow in one direction. - */ - export class SpotLight extends Light { - constructor(hex?: number|string, intensity?: number, distance?: number, angle?: number, exponent?: number, decay?: number); - - /** - * Spotlight focus points at target.position. - * Default position — (0,0,0). - */ - target: Object3D; - - /** - * Light's intensity. - * Default — 1.0. - */ - intensity: number; - - /** - * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. - * Default — 0.0. - */ - distance: number; - - /* - * Maximum extent of the spotlight, in radians, from its direction. - * Default — Math.PI/2. - */ - angle: number; - - /** - * Rapidity of the falloff of light from its target direction. - * Default — 10.0. - */ - exponent: number; - - decay: number; - - shadow: LightShadow; - - clone(recursive?: boolean): SpotLight; - copy(source: PointLight): SpotLight; - } - - // Loaders ////////////////////////////////////////////////////////////////////////////////// - - export interface Progress { - total: number; - loaded: number; - } - - /** - * Base class for implementing loaders. - * - * Events: - * load - * Dispatched when the image has completed loading - * content — loaded image - * - * error - * - * Dispatched when the image can't be loaded - * message — error message - */ - export class Loader { - constructor(); - - /** - * Will be called when load starts. - * The default is a function with empty body. - */ - onLoadStart: () => void; - - /** - * Will be called while load progresses. - * The default is a function with empty body. - */ - onLoadProgress: () => void; - - /** - * Will be called when load completes. - * The default is a function with empty body. - */ - onLoadComplete: () => void; - - /** - * default — null. - * If set, assigns the crossOrigin attribute of the image to the value of crossOrigin, prior to starting the load. - */ - crossOrigin: string; - - extractUrlBase(url: string): string; - initMaterials(materials: Material[], texturePath: string): Material[]; - createMaterial(m: Material, texturePath: string, crossOrigin?: string): boolean; - - static Handlers: LoaderHandler; - } - - export interface LoaderHandler{ - handlers:any[]; - add(regex:string, loader:Loader):void; - get(file: string):Loader; - } - - export class BinaryTextureLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - } - - export class BufferGeometryLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - parse(json: any): BufferGeometry; - } - - export interface Cache { - enabled: boolean; - files: any[]; - - add(key: string, file: any): void; - get(key: string): any; - remove(key: string): void; - clear(): void; - } - export var Cache: Cache; - - export class CompressedTextureLoader{ - constructor(manager?: LoadingManager); - - manager: LoadingManager; - load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - } - - export class CubeTextureLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - - } - - /** - * A loader for loading an image. - * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. - */ - export class ImageLoader { - constructor(manager?: LoadingManager); - - cache: Cache; - manager: LoadingManager; - crossOrigin: string; - - /** - * Begin loading from url - * @param url - */ - load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; - - setCrossOrigin(crossOrigin: string): void; - } - - /** - * A loader for loading objects in JSON format. - */ - export class JSONLoader extends Loader { - constructor(manager?: LoadingManager); - manager: LoadingManager; - withCredentials: boolean; - - load(url: string, onLoad?: (geometry: Geometry, materials: Material[]) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - - setCrossOrigin(crossOrigin: string): void; - setTexturePath( value: string ): void; - parse(json: any, texturePath?: string): { geometry: Geometry; materials?: Material[] }; - } - - /** - * Handles and keeps track of loaded and pending data. - */ - export class LoadingManager { - constructor(onLoad?: () => void, onProgress?: (url: string, loaded: number, total: number) => void, onError?: () => void); - - onStart: () => void; - - /** - * Will be called when load starts. - * The default is a function with empty body. - */ - onLoad: () => void; - - /** - * Will be called while load progresses. - * The default is a function with empty body. - */ - onProgress: (item: any, loaded: number, total: number) => void; - - /** - * Will be called when each element in the scene completes loading. - * The default is a function with empty body. - */ - onError: () => void; - - itemStart(url: string): void; - itemEnd(url: string): void; - itemError(url: string): void; - } - - export var DefaultLoadingManager: LoadingManager; - - export class MaterialLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - textures: { [key:string]:Texture }; - - load(url: string, onLoad: (material: Material) => void): void; - setCrossOrigin(crossOrigin: string): void; - setTextures(textures: { [key:string]:Texture }): void; - getTexture( name: string ):Texture; - parse(json: any): Material; - } - - export class ObjectLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - texturePass: string; - - load(url: string, onLoad?: (object: Object3D) => void): void; - setTexturePath( value: string ): void; - setCrossOrigin(crossOrigin: string): void; - parse(json: any, onLoad?: (object: Object3D) => void): T; - parseGeometries(json: any): any[]; // Array of BufferGeometry or Geometry or Geometry2. - parseMaterials(json: any, textures: Texture[]): Material[]; // Array of Classes that inherits from Matrial. - parseImages( json: any, onLoad: () => void ): any[]; - parseTextures( json: any, images: any ): Texture[]; - parseObject(data: any, geometries: any[], materials: Material[]): T; - - } - - /** - * Class for loading a texture. - * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. - */ - export class TextureLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - crossOrigin: string; - - /** - * Begin loading from url - * - * @param url - */ - load(url: string, onLoad?: (texture: Texture) => void): Texture; - setCrossOrigin(crossOrigin: string): void; - } - - export class XHRLoader { - constructor(manager?: LoadingManager); - - cache: Cache; - manager: LoadingManager; - responseType: string; - crossOrigin: string; - - load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): any; - setResponseType(responseType: string): void; - setCrossOrigin(crossOrigin: string): void; - setWithCredentials( withCredentials: string ): void; - } - - // Materials ////////////////////////////////////////////////////////////////////////////////// - export interface MaterialParameters { - name?: string; - side?: Side; - opacity?: number; - transparent?: boolean; - blending?: Blending; - blendSrc?: BlendingDstFactor; - blendDst?: BlendingSrcFactor; - blendEquation?: BlendingEquation; - depthTest?: boolean; - depthWrite?: boolean; - polygonOffset?: boolean; - polygonOffsetFactor?: number; - polygonOffsetUnits?: number; - alphaTest?: number; - overdraw?: number; - visible?: boolean; - needsUpdate?: boolean; - } - - /** - * Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer. - */ - export class Material { - constructor(); - - /** - * Unique number of this material instance. - */ - id: number; - - uuid: string; - - /** - * Material name. Default is an empty string. - */ - name: string; - - type: string; - - /** - * Defines which of the face sides will be rendered - front, back or both. - * Default is THREE.FrontSide. Other options are THREE.BackSide and THREE.DoubleSide. - */ - side: Side; - - /** - * Opacity. Default is 1. - */ - opacity: number; - - /** - * Defines whether this material is transparent. This has an effect on rendering, as transparent objects need an special treatment, and are rendered after the opaque (i.e. non transparent) objects. For a working example of this behaviour, check the {@link WebGLRenderer} code. - * Default is false. - */ - transparent: boolean; - - /** - * Which blending to use when displaying objects with this material. Default is {@link NormalBlending}. - */ - blending: Blending; - - /** - * Blending source. It's one of the blending mode constants defined in Three.js. Default is {@link SrcAlphaFactor}. - */ - blendSrc: BlendingDstFactor; - - /** - * Blending destination. It's one of the blending mode constants defined in Three.js. Default is {@link OneMinusSrcAlphaFactor}. - */ - blendDst: BlendingSrcFactor; - - /** - * Blending equation to use when applying blending. It's one of the constants defined in Three.js. Default is AddEquation. - */ - blendEquation: BlendingEquation; - - blendSrcAlpha: number; - blendDstAlpha: number; - blendEquationAlpha: number; - - depthFunc: DepthModes; - - /** - * Whether to have depth test enabled when rendering this material. Default is true. - */ - depthTest: boolean; - - /** - * Whether rendering this material has any effect on the depth buffer. Default is true. - * When drawing 2D overlays it can be useful to disable the depth writing in order to layer several things together without creating z-index artifacts. - */ - depthWrite: boolean; - - colorWrite: boolean; - - precision: any; - - /** - * Whether to use polygon offset. Default is false. This corresponds to the POLYGON_OFFSET_FILL WebGL feature. - */ - polygonOffset: boolean; - - /** - * Sets the polygon offset factor. Default is 0. - */ - polygonOffsetFactor: number; - - /** - * Sets the polygon offset units. Default is 0. - */ - polygonOffsetUnits: number; - - /** - * Sets the alpha value to be used when running an alpha test. Default is 0. - */ - alphaTest: number; - - /** - * Enables/disables overdraw. If greater than zero, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is 0. - */ - overdraw: number; - - /** - * Defines whether this material is visible. Default is true. - */ - visible: boolean; - - /** - * Specifies that the material needs to be updated, WebGL wise. Set it to true if you made changes that need to be reflected in WebGL. - * This property is automatically set to true when instancing a new material. - */ - needsUpdate: boolean; - - setValues(values: Object): void; - toJSON(meta?: any): any; - clone(): Material; - clone(source?:Material): Material; - update(): void; - dispose(): void; - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - } - - export interface LineBasicMaterialParameters extends MaterialParameters { - color?: number|string; - linewidth?: number; - linecap?: string; - linejoin?: string; - vertexColors?: Colors; - fog?: boolean; - } - - export class LineBasicMaterial extends Material { - constructor(parameters?: LineBasicMaterialParameters); - - color: Color; - linewidth: number; - linecap: string; - linejoin: string; - vertexColors: Colors; - fog: boolean; - - clone(): LineBasicMaterial; - copy(source: LineBasicMaterial): LineBasicMaterial; - } - - export interface LineDashedMaterialParameters extends MaterialParameters { - color?: number|string; - linewidth?: number; - scale?: number; - dashSize?: number; - gapSize?: number; - vertexColors?: Colors; - fog?: boolean; - } - - export class LineDashedMaterial extends Material { - constructor(parameters?: LineDashedMaterialParameters); - - color: Color; - linewidth: number; - scale: number; - dashSize: number; - gapSize: number; - vertexColors: Colors; - fog: boolean; - - clone(): LineDashedMaterial; - copy(source: LineDashedMaterial): LineDashedMaterial; - } - - /** - * parameters is an object with one or more properties defining the material's appearance. - */ - export interface MeshBasicMaterialParameters extends MaterialParameters{ - color?: number|string; - opacity?: number; - map?: Texture; - aoMap?: Texture; - aoMapIntensity?: number; - specularMap?: Texture; - alphaMap?: Texture; - envMap?: Texture; - combine?: Combine; - reflectivity?: number; - refractionRatio?: number; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - depthWrite?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - fog?: boolean; - } - - export class MeshBasicMaterial extends Material { - constructor(parameters?: MeshBasicMaterialParameters); - - color: Color; - map: Texture; - aoMap: Texture; - aoMapIntensity: number; - specularMap: Texture; - alphaMap: Texture; - envMap: Texture; - combine: Combine; - reflectivity: number; - refractionRatio: number; - fog: boolean; - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - wireframeLinecap: string; - wireframeLinejoin: string; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - - clone(): MeshBasicMaterial; - copy(source: MeshBasicMaterial): MeshBasicMaterial; - } - - export interface MeshDepthMaterialParameters extends MaterialParameters{ - wireframe?: boolean; - wireframeLinewidth?: number; - } - - export class MeshDepthMaterial extends Material { - constructor(parameters?: MeshDepthMaterialParameters); - - wireframe: boolean; - wireframeLinewidth: number; - - clone(): MeshDepthMaterial; - copy(source: MeshDepthMaterial): MeshDepthMaterial; - } - - export interface MeshLambertMaterialParameters extends MaterialParameters{ - color?: number|string; - emissive?: number; - opacity?: number; - map?: Texture; - specularMap?: Texture; - alphaMap?: Texture; - envMap?: Texture; - combine?: Combine; - reflectivity?: number; - refractionRatio?: number; - fog?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - morphNormals?: boolean; - } - - export class MeshLambertMaterial extends Material { - constructor(parameters?: MeshLambertMaterialParameters); - - color: Color; - emissive: Color; - map: Texture; - specularMap: Texture; - alphaMap: Texture; - envMap: Texture; - combine: Combine; - reflectivity: number; - refractionRatio: number; - fog: boolean; - wireframe: boolean; - wireframeLinewidth: number; - wireframeLinecap: string; - wireframeLinejoin: string; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - morphNormals: boolean; - - clone(): MeshLambertMaterial; - copy(source: MeshLambertMaterial): MeshLambertMaterial; - } - - export interface MeshNormalMaterialParameters extends MaterialParameters{ - opacity?: number; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - depthWrite?: boolean; - - /** Render geometry as wireframe. Default is false (i.e. render as smooth shaded). */ - wireframe?: boolean; - /** Controls wireframe thickness. Default is 1. */ - wireframeLinewidth?: number; - - } - - export class MeshNormalMaterial extends Material { - constructor(parameters?: MeshNormalMaterialParameters); - - wireframe: boolean; - wireframeLinewidth: number; - morphTargets: boolean; - - clone(): MeshNormalMaterial; - copy(source: MeshNormalMaterial): MeshNormalMaterial; - } - - export interface MeshPhongMaterialParameters extends MaterialParameters { - /** geometry color in hexadecimal. Default is 0xffffff. */ - color?: number | string; - emissive?: number; - specular?: number; - shininess?: number; - opacity?: number; - map?: Texture; - lightMap?: Texture; - lightMapIntensity?: number; - aoMap?: Texture; - aoMapIntensity?: number; - emissiveMap?: Texture; - bumpMap?: Texture; - bumpScale?: number; - normalMap?: Texture; - normalScale?: Vector2; - displacementMap?: Texture; - displacementScale?: number; - displacementBias?: number; - specularMap?: Texture; - alphaMap?: Texture; - envMap?: Texture; - combine?: Combine; - reflectivity?: number; - refractionRatio?: number; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - depthWrite?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - morphNormals?: boolean; - fog?: boolean; - } - - export class MeshPhongMaterial extends Material { - constructor(parameters?: MeshPhongMaterialParameters); - - color: Color; // diffuse - emissive: Color; - specular: Color; - shininess: number; - metal: boolean; - map: Texture; - lightMap: Texture; - lightMapIntensity: number; - aoMap: Texture; - aoMapIntensity: number; - emissiveMap: Texture; - bumpMap: Texture; - bumpScale: number; - normalMap: Texture; - normalScale: Vector2; - displacementMap: Texture; - displacementScale: number; - displacementBias: number; - specularMap: Texture; - alphaMap: Texture; - envMap: Texture; - combine: Combine; - reflectivity: number; - refractionRatio: number; - fog: boolean; - shading: Shading; - wireframe: boolean; - wireframeLinewidth: number; - wireframeLinecap: string; - wireframeLinejoin: string; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - morphNormals: boolean; - - clone(): MeshPhongMaterial; - copy(source: MeshPhongMaterial): MeshPhongMaterial; - } - - // MultiMaterial does not inherit the Material class in the original code. However, it should treat as Material class. - // See tests/canvas/canvas_materials.ts. - export class MultiMaterial extends Material { - constructor(materials?: Material[]); - materials: Material[]; - - toJSON(): any; - clone(): MultiMaterial; - } - - // deprecated - export class MeshFaceMaterial extends MultiMaterial { - - } - - export interface PointsMaterialParameters extends MaterialParameters{ - color?: number|string; - opacity?: number; - map?: Texture; - size?: number; - sizeAttenuation?: boolean; - blending?: Blending, - depthTest?: boolean; - depthWrite?: boolean; - vertexColors?: Colors; - fog?: boolean; - } - - export class PointsMaterial extends Material { - constructor(parameters?: PointsMaterialParameters); - - color: Color; - map: Texture; - size: number; - sizeAttenuation: boolean; - vertexColors: boolean; - fog: boolean; - - clone(): PointsMaterial; - copy(source: PointsMaterial): PointsMaterial; - } - - export class RawShaderMaterial extends ShaderMaterial { - constructor(parameters?: ShaderMaterialParameters); - } - - export interface ShaderMaterialParameters extends MaterialParameters { - defines?: any; - uniforms?: any; - fragmentShader?: string; - vertexShader?: string; - shading?: Shading; - blending?: Blending; - depthTest?: boolean; - depthWrite?: boolean; - wireframe?: boolean; - wireframeLinewidth?: number; - lights?: boolean; - vertexColors?: Colors; - skinning?: boolean; - morphTargets?: boolean; - morphNormals?: boolean; - fog?: boolean; - } - - export class ShaderMaterial extends Material { - constructor(parameters?: ShaderMaterialParameters); - - defines: any; - uniforms: any; - vertexShader: string; - fragmentShader: string; - shading: Shading; - linewidth: number; - wireframe: boolean; - wireframeLinewidth: number; - fog: boolean; - lights: boolean; - vertexColors: Colors; - skinning: boolean; - morphTargets: boolean; - morphNormals: boolean; - derivatives: boolean; - defaultAttributeValues: any; - index0AttributeName: string; - - clone(): ShaderMaterial; - copy(source: ShaderMaterial): ShaderMaterial; - toJSON(meta: any): any; - } - - export interface SpriteMaterialParameters extends MaterialParameters { - color?: number|string; - opacity?: number; - map?: Texture; - blending?: Blending; - depthTest?: boolean; - depthWrite?: boolean; - uvOffset?: Vector2; - uvScale?: Vector2; - fog?: boolean; - } - - export class SpriteMaterial extends Material { - constructor(parameters?: SpriteMaterialParameters); - - color: Color; - map: Texture; - rotation: number; - fog: boolean; - - clone(): SpriteMaterial; - copy(source: SpriteMaterial): SpriteMaterial; - } - - // Math ////////////////////////////////////////////////////////////////////////////////// - - export class Box2 { - constructor(min?: Vector2, max?: Vector2); - - max: Vector2; - min: Vector2; - - set(min: Vector2, max: Vector2): Box2; - setFromPoints(points: Vector2[]): Box2; - setFromCenterAndSize(center: Vector2, size: Vector2): Box2; - clone(): Box2; - copy(box: Box2): Box2; - makeEmpty(): Box2; - empty(): boolean; - center(optionalTarget?: Vector2): Vector2; - size(optionalTarget?: Vector2): Vector2; - expandByPoint(point: Vector2): Box2; - expandByVector(vector: Vector2): Box2; - expandByScalar(scalar: number): Box2; - containsPoint(point: Vector2): boolean; - containsBox(box: Box2): boolean; - getParameter(point: Vector2): Vector2; - isIntersectionBox(box: Box2): boolean; - clampPoint(point: Vector2, optionalTarget?: Vector2): Vector2; - distanceToPoint(point: Vector2): number; - intersect(box: Box2): Box2; - union(box: Box2): Box2; - translate(offset: Vector2): Box2; - equals(box: Box2): boolean; - } - - export class Box3 { - constructor(min?: Vector3, max?: Vector3); - - max: Vector3; - min: Vector3; - - set(min: Vector3, max: Vector3): Box3; - setFromPoints(points: Vector3[]): Box3; - setFromCenterAndSize(center: Vector3, size: Vector3): Box3; - setFromObject(object: Object3D): Box3; - clone(): Box3; - copy(box: Box3): Box3; - makeEmpty(): Box3; - empty(): boolean; - center(optionalTarget?: Vector3): Vector3; - size(optionalTarget?: Vector3): Vector3; - expandByPoint(point: Vector3): Box3; - expandByVector(vector: Vector3): Box3; - expandByScalar(scalar: number): Box3; - containsPoint(point: Vector3): boolean; - containsBox(box: Box3): boolean; - getParameter(point: Vector3): Vector3; - isIntersectionBox(box: Box3): boolean; - clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - distanceToPoint(point: Vector3): number; - getBoundingSphere(optionalTarget?: Sphere): Sphere; - intersect(box: Box3): Box3; - union(box: Box3): Box3; - applyMatrix4(matrix: Matrix4): Box3; - translate(offset: Vector3): Box3; - equals(box: Box3): boolean; - } - - export interface HSL { - h: number; - s: number; - l: number; - } - - /** - * Represents a color. See also {@link ColorUtils}. - * - * @example - * var color = new THREE.Color( 0xff0000 ); - * - * @see src/math/Color.js - */ - export class Color { - constructor(color?: Color); - constructor(color?: string); - constructor(color?: number); - constructor(r: number, g: number, b: number); - - /** - * Red channel value between 0 and 1. Default is 1. - */ - r: number; - - /** - * Green channel value between 0 and 1. Default is 1. - */ - g: number; - - /** - * Blue channel value between 0 and 1. Default is 1. - */ - b: number; - - set(color: Color): Color; - set(color: number): Color; - set(color: string): Color; - setHex(hex: number): Color; - - /** - * Sets this color from RGB values. - * @param r Red channel value between 0 and 1. - * @param g Green channel value between 0 and 1. - * @param b Blue channel value between 0 and 1. - */ - setRGB(r: number, g: number, b: number): Color; - - /** - * Sets this color from HSL values. - * Based on MochiKit implementation by Bob Ippolito. - * - * @param h Hue channel value between 0 and 1. - * @param s Saturation value channel between 0 and 1. - * @param l Value channel value between 0 and 1. - */ - setHSL(h: number, s: number, l: number): Color; - - /** - * Sets this color from a CSS context style string. - * @param contextStyle Color in CSS context style format. - */ - setStyle(style: string): Color; - - /** - * Clones this color. - */ - clone(): Color; - - /** - * Copies given color. - * @param color Color to copy. - */ - copy(color: Color): Color; - - /** - * Copies given color making conversion from gamma to linear space. - * @param color Color to copy. - */ - copyGammaToLinear(color: Color, gammaFactor?: number): Color; - - /** - * Copies given color making conversion from linear to gamma space. - * @param color Color to copy. - */ - copyLinearToGamma(color: Color, gammaFactor?: number): Color; - - /** - * Converts this color from gamma to linear space. - */ - convertGammaToLinear(): Color; - - /** - * Converts this color from linear to gamma space. - */ - convertLinearToGamma(): Color; - - /** - * Returns the hexadecimal value of this color. - */ - getHex(): number; - - /** - * Returns the string formated hexadecimal value of this color. - */ - getHexString(): string; - - getHSL(): HSL; - - /** - * Returns the value of this color in CSS context style. - * Example: rgb(r, g, b) - */ - getStyle(): string; - - offsetHSL(h: number, s: number, l: number): Color; - - add(color: Color): Color; - addColors(color1: Color, color2: Color): Color; - addScalar(s: number): Color; - multiply(color: Color): Color; - multiplyScalar(s: number): Color; - lerp(color: Color, alpha: number): Color; - equals(color: Color): boolean; - fromArray(rgb: number[], offset?: number): Color; - toArray(array?: number[], offset?: number): number[]; - } - - export class ColorKeywords { - static aliceblue: number; - static antiquewhite: number; - static aqua: number; - static aquamarine: number; - static azure: number; - static beige: number; - static bisque: number; - static black: number; - static blanchedalmond: number; - static blue: number; - static blueviolet: number; - static brown: number; - static burlywood: number; - static cadetblue: number; - static chartreuse: number; - static chocolate: number; - static coral: number; - static cornflowerblue: number; - static cornsilk: number; - static crimson: number; - static cyan: number; - static darkblue: number; - static darkcyan: number; - static darkgoldenrod: number; - static darkgray: number; - static darkgreen: number; - static darkgrey: number; - static darkkhaki: number; - static darkmagenta: number; - static darkolivegreen: number; - static darkorange: number; - static darkorchid: number; - static darkred: number; - static darksalmon: number; - static darkseagreen: number; - static darkslateblue: number; - static darkslategray: number; - static darkslategrey: number; - static darkturquoise: number; - static darkviolet: number; - static deeppink: number; - static deepskyblue: number; - static dimgray: number; - static dimgrey: number; - static dodgerblue: number; - static firebrick: number; - static floralwhite: number; - static forestgreen: number; - static fuchsia: number; - static gainsboro: number; - static ghostwhite: number; - static gold: number; - static goldenrod: number; - static gray: number; - static green: number; - static greenyellow: number; - static grey: number; - static honeydew: number; - static hotpink: number; - static indianred: number; - static indigo: number; - static ivory: number; - static khaki: number; - static lavender: number; - static lavenderblush: number; - static lawngreen: number; - static lemonchiffon: number; - static lightblue: number; - static lightcoral: number; - static lightcyan: number; - static lightgoldenrodyellow: number; - static lightgray: number; - static lightgreen: number; - static lightgrey: number; - static lightpink: number; - static lightsalmon: number; - static lightseagreen: number; - static lightskyblue: number; - static lightslategray: number; - static lightslategrey: number; - static lightsteelblue: number; - static lightyellow: number; - static lime: number; - static limegreen: number; - static linen: number; - static magenta: number; - static maroon: number; - static mediumaquamarine: number; - static mediumblue: number; - static mediumorchid: number; - static mediumpurple: number; - static mediumseagreen: number; - static mediumslateblue: number; - static mediumspringgreen: number; - static mediumturquoise: number; - static mediumvioletred: number; - static midnightblue: number; - static mintcream: number; - static mistyrose: number; - static moccasin: number; - static navajowhite: number; - static navy: number; - static oldlace: number; - static olive: number; - static olivedrab: number; - static orange: number; - static orangered: number; - static orchid: number; - static palegoldenrod: number; - static palegreen: number; - static paleturquoise: number; - static palevioletred: number; - static papayawhip: number; - static peachpuff: number; - static peru: number; - static pink: number; - static plum: number; - static powderblue: number; - static purple: number; - static red: number; - static rosybrown: number; - static royalblue: number; - static saddlebrown: number; - static salmon: number; - static sandybrown: number; - static seagreen: number; - static seashell: number; - static sienna: number; - static silver: number; - static skyblue: number; - static slateblue: number; - static slategray: number; - static slategrey: number; - static snow: number; - static springgreen: number; - static steelblue: number; - static tan: number; - static teal: number; - static thistle: number; - static tomato: number; - static turquoise: number; - static violet: number; - static wheat: number; - static white: number; - static whitesmoke: number; - static yellow: number; - static yellowgreen: number; - } - - export class Euler { - static DefaultOrder: string; - - constructor(x?: number, y?: number, z?: number, order?: string); - - x: number; - y: number; - z: number; - order: string; - - set(x: number, y: number, z: number, order?: string): Euler; - clone(): Euler; - copy(euler: Euler): Euler; - setFromRotationMatrix(m: Matrix4, order?: string, update?: boolean): Euler; - setFromQuaternion(q:Quaternion, order?: string, update?: boolean): Euler; - setFromVector3( v: Vector3, order?: string ): Euler; - reorder(newOrder: string): Euler; - equals(euler: Euler): boolean; - fromArray(xyzo: any[]): Euler; - toArray(array?: number[], offset?: number): number[]; - toVector3(optionalResult?: Vector3): Vector3; - onChange: () => void; - } - - /** - * Frustums are used to determine what is inside the camera's field of view. They help speed up the rendering process. - */ - export class Frustum { - constructor(p0?: Plane, p1?: Plane, p2?: Plane, p3?: Plane, p4?: Plane, p5?: Plane); - - /** - * Array of 6 vectors. - */ - planes: Plane[]; - - set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; - clone(): Frustum; - copy(frustum: Frustum): Frustum; - setFromMatrix(m: Matrix4): Frustum; - intersectsObject(object: Object3D): boolean; - intersectsSphere(sphere: Sphere): boolean; - intersectsBox(box: Box3): boolean; - containsPoint(point: Vector3): boolean; - } - - export class Line3 { - constructor(start?: Vector3, end?: Vector3); - start: Vector3; - end: Vector3; - - set(start?: Vector3, end?: Vector3): Line3; - clone(): Line3; - copy(line: Line3): Line3; - center(optionalTarget?: Vector3): Vector3; - delta(optionalTarget?: Vector3): Vector3; - distanceSq(): number; - distance(): number; - at(t: number, optionalTarget?: Vector3): Vector3; - closestPointToPointParameter(point: Vector3, clampToLine?: boolean): number; - closestPointToPoint(point: Vector3, clampToLine?: boolean, optionalTarget?: Vector3): Vector3; - applyMatrix4(matrix: Matrix4): Line3; - equals(line: Line3): boolean; - } - - interface Math { - generateUUID(): string; - - /** - * Clamps the x to be between a and b. - * - * @param value Value to be clamped. - * @param min Minimum value - * @param max Maximum value. - */ - clamp(value: number, min: number, max: number): number; - euclideanModulo( n: number, m: number ): number; - - /** - * Linear mapping of x from range [a1, a2] to range [b1, b2]. - * - * @param x Value to be mapped. - * @param a1 Minimum value for range A. - * @param a2 Maximum value for range A. - * @param b1 Minimum value for range B. - * @param b2 Maximum value for range B. - */ - mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number; - - smoothstep(x: number, min: number, max: number): number; - - smootherstep(x: number, min: number, max: number): number; - - /** - * Random float from 0 to 1 with 16 bits of randomness. - * Standard Math.random() creates repetitive patterns when applied over larger space. - */ - random16(): number; - - /** - * Random integer from low to high interval. - */ - randInt(low: number, high: number): number; - - /** - * Random float from low to high interval. - */ - randFloat(low: number, high: number): number; - - /** - * Random float from - range / 2 to range / 2 interval. - */ - randFloatSpread(range: number): number; - - degToRad(degrees: number): number; - - radToDeg(radians: number): number; - - isPowerOfTwo(value: number): boolean; - - nearestPowerOfTwo(value: number): number; - - nextPowerOfTwo(value: number): number; - } - - /** - * - * @see src/math/Math.js - */ - export var Math: Math; - - /** - * ( interface Matrix<T> ) - */ - export interface Matrix { - /** - * Float32Array with matrix values. - */ - elements: Float32Array; - - /** - * identity():T; - */ - identity(): Matrix; - - /** - * copy(m:T):T; - */ - copy(m: Matrix): Matrix; - - /** - * multiplyScalar(s:number):T; - */ - multiplyScalar(s: number): Matrix; - - determinant(): number; - - /** - * getInverse(matrix:T, throwOnInvertible?:boolean):T; - */ - getInverse(matrix: Matrix, throwOnInvertible?: boolean): Matrix; - - /** - * transpose():T; - */ - transpose(): Matrix; - - /** - * clone():T; - */ - clone(): Matrix; - } - - /** - * ( class Matrix3 implements Matrix<Matrix3> ) - */ - export class Matrix3 implements Matrix { - /** - * Creates an identity matrix. - */ - constructor(); - - /** - * Initialises the matrix with the supplied n11..n33 values. - */ - constructor(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number); - - /** - * Float32Array with matrix values. - */ - elements: Float32Array; - - set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; - identity(): Matrix3; - clone(): Matrix3; - copy(m: Matrix3): Matrix3; - applyToVector3Array(array: number[], offset?: number, length?: number): number[]; - applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; - multiplyScalar(s: number): Matrix3; - determinant(): number; - getInverse(matrix: Matrix3, throwOnInvertible?: boolean): Matrix3; - getInverse(matrix: Matrix4, throwOnInvertible?: boolean): Matrix3; - - /** - * Transposes this matrix in place. - */ - transpose(): Matrix3; - flattenToArrayOffset(array: number[], offset: number): number[]; - getNormalMatrix(m: Matrix4): Matrix3; - - /** - * Transposes this matrix into the supplied array r, and returns itself. - */ - transposeIntoArray(r: number[]): number[]; - fromArray(array: number[]): Matrix3; - toArray(): number[]; - - } - - /** - * A 4x4 Matrix. - * - * @example - * // Simple rig for rotating around 3 axes - * var m = new THREE.Matrix4(); - * var m1 = new THREE.Matrix4(); - * var m2 = new THREE.Matrix4(); - * var m3 = new THREE.Matrix4(); - * var alpha = 0; - * var beta = Math.PI; - * var gamma = Math.PI/2; - * m1.makeRotationX( alpha ); - * m2.makeRotationY( beta ); - * m3.makeRotationZ( gamma ); - * m.multiplyMatrices( m1, m2 ); - * m.multiply( m3 ); - */ - export class Matrix4 implements Matrix { - /** - * Initialises the matrix with the supplied n11..n44 values. - */ - constructor(n11?: number, n12?: number, n13?: number, n14?: number, n21?: number, n22?: number, n23?: number, n24?: number, n31?: number, n32?: number, n33?: number, n34?: number, n41?: number, n42?: number, n43?: number, n44?: number); - - /** - * Float32Array with matrix values. - */ - elements: Float32Array; - - /** - * Sets all fields of this matrix. - */ - set(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number): Matrix4; - - /** - * Resets this matrix to identity. - */ - identity(): Matrix4; - clone(): Matrix4; - copy(m: Matrix4): Matrix4; - copyPosition(m: Matrix4): Matrix4; - extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; - makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; - - /** - * Copies the rotation component of the supplied matrix m into this matrix rotation component. - */ - extractRotation(m: Matrix4): Matrix4; - makeRotationFromEuler(euler: Euler): Matrix4; - makeRotationFromQuaternion(q: Quaternion): Matrix4; - /** - * Constructs a rotation matrix, looking from eye towards center with defined up vector. - */ - lookAt(eye: Vector3, target: Vector3, up: Vector3): Matrix4; - - /** - * Multiplies this matrix by m. - */ - multiply(m: Matrix4): Matrix4; - - /** - * Sets this matrix to a x b. - */ - multiplyMatrices(a: Matrix4, b: Matrix4): Matrix4; - - /** - * Sets this matrix to a x b and stores the result into the flat array r. - * r can be either a regular Array or a TypedArray. - */ - multiplyToArray(a: Matrix4, b: Matrix4, r: number[]): Matrix4; - - /** - * Multiplies this matrix by s. - */ - multiplyScalar(s: number): Matrix4; - applyToVector3Array(array: number[], offset?: number, length?: number): number[]; - applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; - /** - * Computes determinant of this matrix. - * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm - */ - determinant(): number; - - /** - * Transposes this matrix. - */ - transpose(): Matrix4; - - /** - * Flattens this matrix into supplied flat array starting from offset position in the array. - */ - flattenToArrayOffset(array: number[], offset: number): number[]; - - /** - * Sets the position component for this matrix from vector v. - */ - setPosition(v: Vector3): Vector3; - - /** - * Sets this matrix to the inverse of matrix m. - * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm. - */ - getInverse(m: Matrix4, throwOnInvertible?: boolean): Matrix4; - - /** - * Multiplies the columns of this matrix by vector v. - */ - scale(v: Vector3): Matrix4; - - getMaxScaleOnAxis(): number; - /** - * Sets this matrix as translation transform. - */ - makeTranslation(x: number, y: number, z: number): Matrix4; - - /** - * Sets this matrix as rotation transform around x axis by theta radians. - * - * @param theta Rotation angle in radians. - */ - makeRotationX(theta: number): Matrix4; - - /** - * Sets this matrix as rotation transform around y axis by theta radians. - * - * @param theta Rotation angle in radians. - */ - makeRotationY(theta: number): Matrix4; - - /** - * Sets this matrix as rotation transform around z axis by theta radians. - * - * @param theta Rotation angle in radians. - */ - makeRotationZ(theta: number): Matrix4; - - /** - * Sets this matrix as rotation transform around axis by angle radians. - * Based on http://www.gamedev.net/reference/articles/article1199.asp. - * - * @param axis Rotation axis. - * @param theta Rotation angle in radians. - */ - makeRotationAxis(axis: Vector3, angle: number): Matrix4; - - /** - * Sets this matrix as scale transform. - */ - makeScale(x: number, y: number, z: number): Matrix4; - - /** - * Sets this matrix to the transformation composed of translation, rotation and scale. - */ - compose(translation: Vector3, rotation: Quaternion, scale: Vector3): Matrix4; - - /** - * Decomposes this matrix into the translation, rotation and scale components. - * If parameters are not passed, new instances will be created. - */ - decompose(translation?: Vector3, rotation?: Quaternion, scale?: Vector3): Object[]; // [Vector3, Quaternion, Vector3] - - /** - * Creates a frustum matrix. - */ - makeFrustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; - - /** - * Creates a perspective projection matrix. - */ - makePerspective(fov: number, aspect: number, near: number, far: number): Matrix4; - - /** - * Creates an orthographic projection matrix. - */ - makeOrthographic(left: number, right: number, top: number, bottom: number, near: number, far: number): Matrix4; - equals( matrix: Matrix4 ): boolean; - fromArray(array: number[]): Matrix4; - toArray(): number[]; - } - - export class Plane { - constructor(normal?: Vector3, constant?: number); - - normal: Vector3; - constant: number; - - set(normal: Vector3, constant: number): Plane; - setComponents(x: number, y: number, z: number, w: number): Plane; - setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; - setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; - clone(): Plane; - copy(plane: Plane): Plane; - normalize(): Plane; - negate(): Plane; - distanceToPoint(point: Vector3): number; - distanceToSphere(sphere: Sphere): number; - projectPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - orthoPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - isIntersectionLine(line: Line3): boolean; - intersectLine(line: Line3, optionalTarget?: Vector3): Vector3; - coplanarPoint(optionalTarget?: boolean): Vector3; - applyMatrix4(matrix: Matrix4, optionalNormalMatrix?: Matrix3): Plane; - translate(offset: Vector3): Plane; - equals(plane: Plane): boolean; - } - - /** - * Implementation of a quaternion. This is used for rotating things without incurring in the dreaded gimbal lock issue, amongst other advantages. - * - * @example - * var quaternion = new THREE.Quaternion(); - * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); - * var vector = new THREE.Vector3( 1, 0, 0 ); - * vector.applyQuaternion( quaternion ); - */ - export class Quaternion { - /** - * @param x x coordinate - * @param y y coordinate - * @param z z coordinate - * @param w w coordinate - */ - constructor(x?: number, y?: number, z?: number, w?: number); - - x: number; - y: number; - z: number; - w: number; - - /** - * Sets values of this quaternion. - */ - set(x: number, y: number, z: number, w: number): Quaternion; - - /** - * Clones this quaternion. - */ - clone(): Quaternion; - - /** - * Copies values of q to this quaternion. - */ - copy(q: Quaternion): Quaternion; - - /** - * Sets this quaternion from rotation specified by Euler angles. - */ - setFromEuler(euler: Euler, update?: boolean): Quaternion; - - /** - * Sets this quaternion from rotation specified by axis and angle. - * Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm. - * Axis have to be normalized, angle is in radians. - */ - setFromAxisAngle(axis: Vector3, angle: number): Quaternion; - - /** - * Sets this quaternion from rotation component of m. Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm. - */ - setFromRotationMatrix(m: Matrix4): Quaternion; - setFromUnitVectors(vFrom: Vector3, vTo: Vector3): Quaternion; - /** - * Inverts this quaternion. - */ - inverse(): Quaternion; - - conjugate(): Quaternion; - dot(v: Vector3): number; - lengthSq(): number; - - /** - * Computes length of this quaternion. - */ - length(): number; - - /** - * Normalizes this quaternion. - */ - normalize(): Quaternion; - - /** - * Multiplies this quaternion by b. - */ - multiply(q: Quaternion): Quaternion; - - /** - * Sets this quaternion to a x b - * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm. - */ - multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; - - /** - * Deprecated. Use Vector3.applyQuaternion instead - */ - multiplyVector3(vector: Vector3): Vector3; - slerp(qb: Quaternion, t: number): Quaternion; - equals(v: Quaternion): boolean; - fromArray(n: number[]): Quaternion; - toArray(): number[]; - - fromArray(xyzw: number[], offset?: number): Quaternion; - toArray(xyzw?: number[], offset?: number): number[]; - - onChange: () => void; - - /** - * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/. - */ - static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: number): Quaternion; - } - - export class Ray { - constructor(origin?: Vector3, direction?: Vector3); - - origin: Vector3; - direction: Vector3; - - set(origin: Vector3, direction: Vector3): Ray; - clone(): Ray; - copy(ray: Ray): Ray; - at(t: number, optionalTarget?: Vector3): Vector3; - recast(t: number): Ray; - closestPointToPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - distanceToPoint(point: Vector3): number; - distanceSqToPoint(point: Vector3): number; - distanceSqToSegment(v0: Vector3, v1: Vector3, optionalPointOnRay?: Vector3, optionalPointOnSegment?: Vector3): number; - isIntersectionSphere(sphere: Sphere): boolean; - intersectSphere(sphere: Sphere, optionalTarget?: Vector3): Vector3; - isIntersectionPlane(plane: Plane): boolean; - distanceToPlane(plane: Plane): number; - intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; - isIntersectionBox(box: Box3): boolean; - intersectBox(box: Box3, optionalTarget?: Vector3): Vector3; - intersectTriangle(a: Vector3, b: Vector3, c: Vector3, backfaceCulling: boolean, optionalTarget?: Vector3): Vector3; - applyMatrix4(matrix4: Matrix4): Ray; - equals(ray: Ray): boolean; - } - - export class Sphere { - constructor(center?: Vector3, radius?: number); - - center: Vector3; - radius: number; - - set(center: Vector3, radius: number): Sphere; - setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; - clone(): Sphere; - copy(sphere: Sphere): Sphere; - empty(): boolean; - containsPoint(point: Vector3): boolean; - distanceToPoint(point: Vector3): number; - intersectsSphere(sphere: Sphere): boolean; - clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - getBoundingBox(optionalTarget?: Box3): Box3; - applyMatrix4(matrix: Matrix4): Sphere; - translate(offset: Vector3): Sphere; - equals(sphere: Sphere): boolean; - } - - export interface SplineControlPoint { - x: number; - y: number; - z: number; - } - - /** - * Represents a spline. - * - * @see src/math/Spline.js - */ - export class Spline { - /** - * Initialises the spline with points, which are the places through which the spline will go. - */ - constructor(points: SplineControlPoint[]); - - points: SplineControlPoint[]; - - /** - * Initialises using the data in the array as a series of points. Each value in a must be another array with three values, where a[n] is v, the value for the nth point, and v[0], v[1] and v[2] are the x, y and z coordinates of that point n, respectively. - * - * @param a array of triplets containing x, y, z coordinates - */ - initFromArray(a: number[][]): void; - - /** - * Return the interpolated point at k. - * - * @param k point index - */ - getPoint(k: number): SplineControlPoint; - - /** - * Returns an array with triplets of x, y, z coordinates that correspond to the current control points. - */ - getControlPointsArray(): number[][]; - - /** - * Returns the length of the spline when using nSubDivisions. - * @param nSubDivisions number of subdivisions between control points. Default is 100. - */ - getLength(nSubDivisions?: number): { chunks: number[]; total: number; }; - - /** - * Modifies the spline so that it looks similar to the original but has its points distributed in such way that moving along the spline it's done at a more or less constant speed. The points should also appear more uniformly spread along the curve. - * This is done by resampling the original spline, with the density of sampling controlled by samplingCoef. Here it's interesting to note that denser sampling is not necessarily better: if sampling is too high, you may get weird kinks in curvature. - * - * @param samplingCoef how many intermediate values to use between spline points - */ - reparametrizeByArcLength(samplingCoef: number): void; - } - - class Triangle { - constructor(a?: Vector3, b?: Vector3, c?: Vector3); - - a: Vector3; - b: Vector3; - c: Vector3; - - set(a: Vector3, b: Vector3, c: Vector3): Triangle; - setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; - clone(): Triangle; - copy(triangle: Triangle): Triangle; - area(): number; - midpoint(optionalTarget?: Vector3): Vector3; - normal(optionalTarget?: Vector3): Vector3; - plane(optionalTarget?: Vector3): Plane; - barycoordFromPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - containsPoint(point: Vector3): boolean; - equals(triangle: Triangle): boolean; - - static normal(a: Vector3, b: Vector3, c: Vector3, optionalTarget?: Vector3): Vector3; - static barycoordFromPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3, optionalTarget: Vector3): Vector3; - static containsPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3): boolean; - } - - - /** - * ( interface Vector<T> ) - * - * Abstract interface of Vector2, Vector3 and Vector4. - * Currently the members of Vector is NOT type safe because it accepts different typed vectors. - * Those definitions will be changed when TypeScript innovates Generics to be type safe. - * - * @example - * var v:THREE.Vector = new THREE.Vector3(); - * v.addVectors(new THREE.Vector2(0, 1), new THREE.Vector2(2, 3)); // invalid but compiled successfully - */ - export interface Vector { - setComponent(index: number, value: number): void; - - getComponent(index: number): number; - - /** - * copy(v:T):T; - */ - copy(v: Vector): Vector; - - /** - * add(v:T):T; - */ - add(v: Vector): Vector; - - /** - * addVectors(a:T, b:T):T; - */ - addVectors(a: Vector, b: Vector): Vector; - - /** - * sub(v:T):T; - */ - sub(v: Vector): Vector; - - /** - * subVectors(a:T, b:T):T; - */ - subVectors(a: Vector, b: Vector): Vector; - - /** - * multiplyScalar(s:number):T; - */ - multiplyScalar(s: number): Vector; - - /** - * divideScalar(s:number):T; - */ - divideScalar(s: number): Vector; - - /** - * negate():T; - */ - negate(): Vector; - - /** - * dot(v:T):T; - */ - dot(v: Vector): number; - - /** - * lengthSq():number; - */ - lengthSq(): number; - - /** - * length():number; - */ - length(): number; - - /** - * normalize():T; - */ - normalize(): Vector; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceTo(v:T):number; - */ - distanceTo?(v: Vector): number; - - /** - * NOTE: Vector4 doesn't have the property. - * - * distanceToSquared(v:T):number; - */ - distanceToSquared?(v: Vector): number; - - /** - * setLength(l:number):T; - */ - setLength(l: number): Vector; - - /** - * lerp(v:T, alpha:number):T; - */ - lerp(v: Vector, alpha: number): Vector; - - /** - * equals(v:T):boolean; - */ - equals(v: Vector): boolean; - - /** - * clone():T; - */ - clone(): Vector; - } - - /** - * 2D vector. - * - * ( class Vector2 implements Vector ) - */ - export class Vector2 implements Vector { - constructor(x?: number, y?: number); - - x: number; - y: number; - - width: number; - height: number; - - /** - * Sets value of this vector. - */ - set(x: number, y: number): Vector2; - - /** - * Sets X component of this vector. - */ - setX(x: number): Vector2; - - /** - * Sets Y component of this vector. - */ - setY(y: number): Vector2; - - /** - * Sets a component of this vector. - */ - setComponent(index: number, value: number): void; - - /** - * Gets a component of this vector. - */ - getComponent(index: number): number; - /** - * Clones this vector. - */ - clone(): Vector2; - /** - * Copies value of v to this vector. - */ - copy(v: Vector2): Vector2; - - /** - * Adds v to this vector. - */ - add(v: Vector2): Vector2; - - /** - * Sets this vector to a + b. - */ - addScalar(s: number): Vector2; - addVectors(a: Vector2, b: Vector2): Vector2; - addScaledVector( v: Vector2, s: number ): Vector2; - /** - * Subtracts v from this vector. - */ - sub(v: Vector2): Vector2; - - /** - * Sets this vector to a - b. - */ - subVectors(a: Vector2, b: Vector2): Vector2; - - multiply(v: Vector2): Vector2; - /** - * Multiplies this vector by scalar s. - */ - multiplyScalar(scalar: number): Vector2; - - divide(v: Vector2): Vector2; - /** - * Divides this vector by scalar s. - * Set vector to ( 0, 0 ) if s == 0. - */ - divideScalar(s: number): Vector2; - - min(v: Vector2): Vector2; - - max(v: Vector2): Vector2; - clamp(min: Vector2, max: Vector2): Vector2; - clampScalar(min: number, max: number): Vector2; - clampLength(min: number, max: number): Vector2; - floor(): Vector2; - ceil(): Vector2; - round(): Vector2; - roundToZero(): Vector2; - - /** - * Inverts this vector. - */ - negate(): Vector2; - - /** - * Computes dot product of this vector and v. - */ - dot(v: Vector2): number; - - /** - * Computes squared length of this vector. - */ - lengthSq(): number; - - /** - * Computes length of this vector. - */ - length(): number; - lengthManhattan(): number; - - /** - * Normalizes this vector. - */ - normalize(): Vector2; - - /** - * Computes distance of this vector to v. - */ - distanceTo(v: Vector2): number; - - /** - * Computes squared distance of this vector to v. - */ - distanceToSquared(v: Vector2): number; - - /** - * Normalizes this vector and multiplies it by l. - */ - setLength(length: number): Vector2; - - lerp(v: Vector2, alpha: number): Vector2; - - lerpVectors(v1: Vector2, v2: Vector2, alpha: number): Vector2; - - /** - * Checks for strict equality of this vector and v. - */ - equals(v: Vector2): boolean; - - fromArray(xy: number[], offset?: number): Vector2; - - toArray(xy?: number[], offset?: number): number[]; - - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector2; - - rotateAround( center: Vector2, angle: number ): Vector2; - } - - /** - * 3D vector. - * - * @example - * var a = new THREE.Vector3( 1, 0, 0 ); - * var b = new THREE.Vector3( 0, 1, 0 ); - * var c = new THREE.Vector3(); - * c.crossVectors( a, b ); - * - * @see src/math/Vector3.js - * - * ( class Vector3 implements Vector ) - */ - export class Vector3 implements Vector { - - constructor(x?: number, y?: number, z?: number); - - x: number; - y: number; - z: number; - - /** - * Sets value of this vector. - */ - set(x: number, y: number, z: number): Vector3; - - /** - * Sets x value of this vector. - */ - setX(x: number): Vector3; - - /** - * Sets y value of this vector. - */ - setY(y: number): Vector3; - - /** - * Sets z value of this vector. - */ - setZ(z: number): Vector3; - - setComponent(index: number, value: number): void; - getComponent(index: number): number; - /** - * Clones this vector. - */ - clone(): Vector3; - /** - * Copies value of v to this vector. - */ - copy(v: Vector3): Vector3; - - /** - * Adds v to this vector. - */ - add(a: Vector3): Vector3; - addScalar(s: number): Vector3; - addScaledVector(v: Vector3, s: number): Vector3; - - /** - * Sets this vector to a + b. - */ - addVectors(a: Vector3, b: Vector3): Vector3; - addScaledVector( v: Vector3, s: number ): Vector3; - - /** - * Subtracts v from this vector. - */ - sub(a: Vector3): Vector3; - - subScalar( s: number ): Vector3; - - /** - * Sets this vector to a - b. - */ - subVectors(a: Vector3, b: Vector3): Vector3; - - multiply(v: Vector3): Vector3; - /** - * Multiplies this vector by scalar s. - */ - multiplyScalar(s: number): Vector3; - multiplyVectors(a: Vector3, b: Vector3): Vector3; - applyEuler(euler: Euler): Vector3; - applyAxisAngle(axis: Vector3, angle: number): Vector3; - applyMatrix3(m: Matrix3): Vector3; - applyMatrix4(m: Matrix4): Vector3; - applyProjection(m: Matrix4): Vector3; - applyQuaternion(q: Quaternion): Vector3; - project(camrea: Camera): Vector3; - unproject(camera: Camera): Vector3; - transformDirection(m: Matrix4): Vector3; - divide(v: Vector3): Vector3; - - /** - * Divides this vector by scalar s. - * Set vector to ( 0, 0, 0 ) if s == 0. - */ - divideScalar(s: number): Vector3; - min(v: Vector3): Vector3; - max(v: Vector3): Vector3; - clamp(min: Vector3, max: Vector3): Vector3; - clampScalar(min: number, max: number): Vector3; - clampLength(min: number, max: number): Vector3; - floor(): Vector3; - ceil(): Vector3; - round(): Vector3; - roundToZero(): Vector3; - - /** - * Inverts this vector. - */ - negate(): Vector3; - - /** - * Computes dot product of this vector and v. - */ - dot(v: Vector3): number; - - /** - * Computes squared length of this vector. - */ - lengthSq(): number; - - /** - * Computes length of this vector. - */ - length(): number; - - /** - * Computes Manhattan length of this vector. - * http://en.wikipedia.org/wiki/Taxicab_geometry - */ - lengthManhattan(): number; - - /** - * Normalizes this vector. - */ - normalize(): Vector3; - - /** - * Normalizes this vector and multiplies it by l. - */ - setLength(l: number): Vector3; - lerp(v: Vector3, alpha: number): Vector3; - - lerpVectors(v1: Vector3, v2: Vector3, alpha: number): Vector3; - - /** - * Sets this vector to cross product of itself and v. - */ - cross(a: Vector3): Vector3; - - /** - * Sets this vector to cross product of a and b. - */ - crossVectors(a: Vector3, b: Vector3): Vector3; - projectOnVector(v: Vector3): Vector3; - projectOnPlane(planeNormal: Vector3): Vector3; - reflect(vector: Vector3): Vector3; - angleTo(v: Vector3): number; - - /** - * Computes distance of this vector to v. - */ - distanceTo(v: Vector3): number; - - /** - * Computes squared distance of this vector to v. - */ - distanceToSquared(v: Vector3): number; - - setFromMatrixPosition(m: Matrix4): Vector3; - setFromMatrixScale(m: Matrix4): Vector3; - setFromMatrixColumn(index: number, matrix: Matrix4): Vector3; - - /** - * Checks for strict equality of this vector and v. - */ - equals(v: Vector3): boolean; - - fromArray(xyz: number[], offset?: number): Vector3; - - toArray(xyz?: number[], offset?: number): number[]; - - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector3; - } - - /** - * 4D vector. - * - * ( class Vector4 implements Vector ) - */ - export class Vector4 implements Vector { - constructor(x?: number, y?: number, z?: number, w?: number); - x: number; - y: number; - z: number; - w: number; - - /** - * Sets value of this vector. - */ - set(x: number, y: number, z: number, w: number): Vector4; - - /** - * Sets X component of this vector. - */ - setX(x: number): Vector4; - - /** - * Sets Y component of this vector. - */ - setY(y: number): Vector4; - - /** - * Sets Z component of this vector. - */ - setZ(z: number): Vector4; - - /** - * Sets w component of this vector. - */ - setW(w: number): Vector4; - - setComponent(index: number, value: number): void; - getComponent(index: number): number; - /** - * Clones this vector. - */ - clone(): Vector4; - /** - * Copies value of v to this vector. - */ - copy(v: Vector4): Vector4; - - /** - * Adds v to this vector. - */ - add(v: Vector4): Vector4; - addScalar(s: number): Vector4; - - /** - * Sets this vector to a + b. - */ - addVectors(a: Vector4, b: Vector4): Vector4; - addScaledVector( v: Vector4, s: number ): Vector4; - /** - * Subtracts v from this vector. - */ - sub(v: Vector4): Vector4; - - subScalar(s: number): Vector4; - - /** - * Sets this vector to a - b. - */ - subVectors(a: Vector4, b: Vector4): Vector4; - - /** - * Multiplies this vector by scalar s. - */ - multiplyScalar(s: number): Vector4; - applyMatrix4(m: Matrix4): Vector4; - - /** - * Divides this vector by scalar s. - * Set vector to ( 0, 0, 0 ) if s == 0. - */ - divideScalar(s: number): Vector4; - - /** - * http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm - * @param q is assumed to be normalized - */ - setAxisAngleFromQuaternion(q: Quaternion): Vector4; - - /** - * http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm - * @param m assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) - */ - setAxisAngleFromRotationMatrix(m: Matrix4): Vector4; - - min(v: Vector4): Vector4; - max(v: Vector4): Vector4; - clamp(min: Vector4, max: Vector4): Vector4; - clampScalar(min: number, max: number): Vector4; - floor(): Vector4; - ceil(): Vector4; - round(): Vector4; - roundToZero(): Vector4; - - /** - * Inverts this vector. - */ - negate(): Vector4; - - /** - * Computes dot product of this vector and v. - */ - dot(v: Vector4): number; - - /** - * Computes squared length of this vector. - */ - lengthSq(): number; - - /** - * Computes length of this vector. - */ - length(): number; - lengthManhattan(): number; - - /** - * Normalizes this vector. - */ - normalize(): Vector4; - /** - * Normalizes this vector and multiplies it by l. - */ - setLength(length: number): Vector4; - - /** - * Linearly interpolate between this vector and v with alpha factor. - */ - lerp(v: Vector4, alpha: number): Vector4; - - lerpVectors(v1: Vector4, v2: Vector4, alpha: number): Vector4; - - /** - * Checks for strict equality of this vector and v. - */ - equals(v: Vector4): boolean; - - fromArray(xyzw: number[], offset?: number): Vector4; - - toArray(xyzw?: number[], offset?: number): number[]; - - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector4; - } - - // Objects ////////////////////////////////////////////////////////////////////////////////// - - export class Bone extends Object3D { - constructor(skin: SkinnedMesh); - - skin: SkinnedMesh; - - clone(): Bone; - copy(source: Bone): Bone; - } - - export class Group extends Object3D { - constructor(); - } - - export class LOD extends Object3D { - constructor(); - - levels: any[]; - - addLevel(object: Object3D, distance?: number): void; - getObjectForDistance(distance: number): Object3D; - raycast(raycaster: Raycaster, intersects: any): void; - update(camera: Camera): void; - - clone(): LOD; - copy(source: LOD): LOD; - toJSON(meta: any): any; - } - - export interface LensFlareProperty { - texture: Texture; // Texture - size: number; // size in pixels (-1 = use texture.width) - distance: number; // distance (0-1) from light source (0=at light source) - x: number; - y: number; - z: number; // screen position (-1 => 1) z = 0 is ontop z = 1 is back - scale: number; // scale - rotation: number; // rotation - opacity: number; // opacity - color: Color; // color - blending: Blending; - } - - export class LensFlare extends Object3D { - constructor(texture?: Texture, size?: number, distance?: number, blending?: Blending, color?: Color); - - lensFlares: LensFlareProperty[]; - positionScreen: Vector3; - customUpdateCallback: (object: LensFlare) => void; - - add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; - add(obj: Object3D): void; - - updateLensFlares(): void; - - clone(): LensFlare; - copy(source: LensFlare): LensFlare; - } - - export class Line extends Object3D { - constructor( - geometry?: Geometry | BufferGeometry, - material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, - mode?: number - ); - - geometry: Geometry|BufferGeometry; - material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial - - raycast(raycaster: Raycaster, intersects: any): void; - clone(): Line; - copy(source: Line): Line; - } - - export class LineSegments extends Line { - constructor( - geometry?: Geometry | BufferGeometry, - material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, - mode?: number - ); - - clone(): LineSegments; - copy(source: LineSegments): LineSegments; - } - - enum LineMode{} - var LineStrip: LineMode; - var LinePieces: LineMode; - - export class Mesh extends Object3D { - constructor(geometry?: Geometry, material?: Material); - constructor(geometry?: BufferGeometry, material?: Material); - - geometry: Geometry|BufferGeometry; - material: Material; - - updateMorphTargets(): void; - getMorphTargetIndexByName(name: string): number; - raycast(raycaster: Raycaster, intersects: any): void; - clone(): Mesh; - copy(source: Mesh): Mesh; - } - - /** - * A class for displaying particles in the form of variable size points. For example, if using the WebGLRenderer, the particles are displayed using GL_POINTS. - * - * @see src/objects/ParticleSystem.js - */ - export class Points extends Object3D { - - /** - * @param geometry An instance of Geometry. - * @param material An instance of Material (optional). - */ - constructor( - geometry: Geometry | BufferGeometry, - material?: PointsMaterial | ShaderMaterial - ); - - /** - * An instance of Geometry, where each vertex designates the position of a particle in the system. - */ - geometry: Geometry; - - /** - * An instance of Material, defining the object's appearance. Default is a ParticleBasicMaterial with randomised colour. - */ - material: Material; - - raycast(raycaster: Raycaster, intersects: any): void; - clone(): Points; - copy(source: Points): Points; - } - - export class Skeleton { - constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); - - useVertexTexture: boolean; - identityMatrix: Matrix4; - bones: Bone[]; - boneTextureWidth: number; - boneTextureHeight: number; - boneMatrices: Float32Array; - boneTexture: DataTexture; - boneInverses: Matrix4[]; - - calculateInverses(bone: Bone): void; - pose(): void; - update(): void; - clone(): Skeleton; - - } - - export class SkinnedMesh extends Mesh { - constructor(geometry?: Geometry|BufferGeometry, material?: MeshBasicMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: MeshDepthMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: MeshFaceMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: MeshLambertMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: MeshNormalMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: ShaderMaterial, useVertexTexture?: boolean); - - bindMode: string; - bindMatrix: Matrix4; - bindMatrixInverse: Matrix4; - - bind( skeleton: Skeleton, bindMatrix?: Matrix4 ): void; - pose(): void; - normalizeSkinWeights(): void; - updateMatrixWorld(force?: boolean): void; - clone(): SkinnedMesh; - copy(source?: SkinnedMesh): SkinnedMesh; - - skeleton: Skeleton; - } - - export class Sprite extends Object3D { - constructor(material?: Material); - - geometry: BufferGeometry; - material: SpriteMaterial; - - raycast(raycaster: Raycaster, intersects: any): void; - clone(): Sprite; - copy(source?: Sprite): Sprite; - } - - - // Renderers ////////////////////////////////////////////////////////////////////////////////// - - export interface Renderer { - render(scene: Scene, camera: Camera): void; - setSize(width:number, height:number, updateStyle?:boolean): void; - domElement: HTMLCanvasElement; - } - - export interface WebGLRendererParameters { - /** - * A Canvas where the renderer draws its output. - */ - canvas?: HTMLCanvasElement; - - /** - * shader precision. Can be "highp", "mediump" or "lowp". - */ - precision?: string; - - /** - * default is true. - */ - alpha?: boolean; - - /** - * default is true. - */ - premultipliedAlpha?: boolean; - - /** - * default is false. - */ - antialias?: boolean; - - /** - * default is true. - */ - stencil?: boolean; - - /** - * default is false. - */ - preserveDrawingBuffer?: boolean; - - /** - * default is 0x000000. - */ - clearColor?: number; - - /** - * default is 0. - */ - clearAlpha?: number; - - devicePixelRatio?: number; - - /** - * default is false. - */ - logarithmicDepthBuffer?: boolean; - } - - - /** - * The WebGL renderer displays your beautifully crafted scenes using WebGL, if your device supports it. - * This renderer has way better performance than CanvasRenderer. - * - * @see src/renderers/WebGLRenderer.js - */ - export class WebGLRenderer implements Renderer { - /** - * parameters is an optional object with properties defining the renderer's behaviour. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing. - */ - constructor(parameters?: WebGLRendererParameters); - - /** - * A Canvas where the renderer draws its output. - * This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page. - */ - domElement: HTMLCanvasElement; - - /** - * The HTML5 Canvas's 'webgl' context obtained from the canvas where the renderer will draw. - */ - context: WebGLRenderingContext; - - /** - * Defines whether the renderer should automatically clear its output before rendering. - */ - autoClear: boolean; - - /** - * If autoClear is true, defines whether the renderer should clear the color buffer. Default is true. - */ - autoClearColor: boolean; - - /** - * If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true. - */ - autoClearDepth: boolean; - - /** - * If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true. - */ - autoClearStencil: boolean; - - /** - * Defines whether the renderer should sort objects. Default is true. - */ - sortObjects: boolean; - - extensions: WebGLExtensions; - - gammaFactor: number; - - /** - * Default is false. - */ - gammaInput: boolean; - - /** - * Default is false. - */ - gammaOutput: boolean; - - /** - * Default is false. - */ - shadowMapEnabled: boolean; - - /** - * Defines shadow map type (unfiltered, percentage close filtering, percentage close filtering with bilinear filtering in shader) - * Options are THREE.BasicShadowMap, THREE.PCFShadowMap, THREE.PCFSoftShadowMap. Default is THREE.PCFShadowMap. - */ - shadowMapType: ShadowMapType; - - /** - * Default is true - */ - shadowMapCullFace: CullFace; - - /** - * Default is false. - */ - shadowMapDebug: boolean; - - /** - * Default is 8. - */ - maxMorphTargets: number; - - /** - * Default is 4. - */ - maxMorphNormals: number; - - /** - * Default is true. - */ - autoScaleCubemaps: boolean; - - /** - * An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields: - */ - info: { - memory: { - programs: number; - geometries: number; - textures: number; - }; - render: { - calls: number; - vertices: number; - faces: number; - points: number; - }; - }; - - shadowMap: WebGLShadowMapInstance; - - /** - * Return the WebGL context. - */ - getContext(): WebGLRenderingContext; - - forceContextLoss(): void; - - capabilities: WebGLCapabilities; - - /** Deprecated, use capabilities instead */ - supportsVertexTextures(): boolean; - supportsFloatTextures(): boolean; - supportsStandardDerivatives(): boolean; - supportsCompressedTextureS3TC(): boolean; - supportsCompressedTexturePVRTC(): boolean; - supportsBlendMinMax(): boolean; - getPrecision(): string; - - getMaxAnisotropy(): number; - getPixelRatio(): number; - setPixelRatio(value: number): void; - - getSize(): { width: number; height: number; }; - - /** - * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). - */ - setSize(width: number, height: number, updateStyle?: boolean): void; - - /** - * Sets the viewport to render from (x, y) to (x + width, y + height). - */ - setViewport(x?: number, y?: number, width?: number, height?: number): void; - - /** - * Sets the scissor area from (x, y) to (x + width, y + height). - */ - setScissor(x: number, y: number, width: number, height: number): void; - - /** - * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. - */ - enableScissorTest(enable: boolean): void; - - /** - * Sets the clear color, using color for the color and alpha for the opacity. - */ - setClearColor(color: Color, alpha?: number): void; - setClearColor(color: string, alpha?: number): void; - setClearColor(color: number, alpha?: number): void; - - setClearAlpha(alpha: number): void; - - /** - * Sets the clear color, using hex for the color and alpha for the opacity. - * - * @example - * // Creates a renderer with black background - * var renderer = new THREE.WebGLRenderer(); - * renderer.setSize(200, 100); - * renderer.setClearColorHex(0x000000, 1); - */ - setClearColorHex(hex: number, alpha: number): void; - - /** - * Returns a THREE.Color instance with the current clear color. - */ - getClearColor(): Color; - - /** - * Returns a float with the current clear alpha. Ranges from 0 to 1. - */ - getClearAlpha(): number; - - /** - * Tells the renderer to clear its color, depth or stencil drawing buffer(s). - * Arguments default to true - */ - clear(color?: boolean, depth?: boolean, stencil?: boolean): void; - - clearColor(): void; - clearDepth(): void; - clearStencil(): void; - clearTarget(renderTarget:WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; - resetGLState(): void; - dispose(): void; - - /** - * Tells the shadow map plugin to update using the passed scene and camera parameters. - * - * @param scene an instance of Scene - * @param camera — an instance of Camera - */ - updateShadowMap(scene: Scene, camera: Camera): void; - - renderBufferImmediate(object: Object3D, program: Object, material: Material): void; - - renderBufferDirect(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - - renderBuffer(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - - /** - * Render a scene using a camera. - * The render is done to the renderTarget (if specified) or to the canvas as usual. - * If forceClear is true, the canvas will be cleared before rendering, even if the renderer's autoClear property is false. - */ - render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; - renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; - - /** - * Used for setting the gl frontFace, cullFace states in the GPU, thus enabling/disabling face culling when rendering. - * If cullFace is false, culling will be disabled. - * @param cullFace "back", "front", "front_and_back", or false. - * @param frontFace "ccw" or "cw - */ - setFaceCulling(cullFace?: CullFace, frontFace?: FrontFaceDirection): void; - setMaterialFaces(material: Material): void; - setDepthTest(depthTest: boolean): void; - setDepthWrite(depthWrite: boolean): void; - setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; - uploadTexture(texture: Texture): void; - setTexture(texture: Texture, slot: number): void; - setRenderTarget(renderTarget: RenderTarget): void; - readRenderTargetPixels( renderTarget: RenderTarget, x: number, y: number, width: number, height: number, buffer: any ): void; - } - - export interface RenderTarget { - } - - export interface WebGLRenderTargetOptions { - wrapS?: Wrapping; - wrapT?: Wrapping; - magFilter?: TextureFilter; - minFilter?: TextureFilter; - anisotropy?: number; // 1; - format?: number; // RGBAFormat; - type?: TextureDataType; // UnsignedByteType; - depthBuffer?: boolean; // true; - stencilBuffer?: boolean; // true; - } - - export class WebGLRenderTarget implements RenderTarget { - constructor(width: number, height: number, options?: WebGLRenderTargetOptions); - - uuid: string; - width: number; - height: number; - wrapS: Wrapping; - wrapT: Wrapping; - magFilter: TextureFilter; - minFilter: TextureFilter; - anisotropy: number; - offset: Vector2; - repeat: Vector2; - format: number; - type: number; - depthBuffer: boolean; - stencilBuffer: boolean; - generateMipmaps: boolean; - shareDepthFrom: any; - - setSize(width: number, height: number): void; - clone(): WebGLRenderTarget; - copy(source: WebGLRenderTarget): WebGLRenderTarget; - dispose(): void; - - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - } - - export class WebGLRenderTargetCube extends WebGLRenderTarget { - constructor(width: number, height: number, options?: WebGLRenderTargetOptions); - - activeCubeFace: number; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 - } - - // Renderers / Shaders ///////////////////////////////////////////////////////////////////// - export interface ShaderChunk { - [name: string]: string; - - common: string; - - alphamap_fragment: string; - alphamap_pars_fragment: string; - alphatest_fragment: string; - aomap_fragment: string; - aomap_pars_fragment: string; - begin_vertex: string; - beginnormal_vertex: string; - bumpmap_pars_fragment: string; - color_fragment: string; - color_pars_fragment: string; - color_pars_vertex: string; - color_vertex: string; - defaultnormal_vertex: string; - displacementmap_pars_vertex: string; - displacementmap_vertex: string; - emissivemap_fragment: string; - emissivemap_pars_fragment: string; - envmap_fragment: string; - envmap_pars_fragment: string; - envmap_pars_vertex: string; - envmap_vertex: string; - fog_fragment: string; - fog_pars_fragment: string; - hemilight_fragment: string; - lightmap_fragment: string; - lightmap_pars_fragment: string; - lights_lambert_pars_vertex: string; - lights_lambert_vertex: string; - lights_phong_fragment: string; - lights_phong_pars_fragment: string; - lights_phong_pars_vertex: string; - lights_phong_vertex: string; - linear_to_gamma_fragment: string; - logdepthbuf_fragment: string; - logdepthbuf_pars_fragment: string; - logdepthbuf_pars_vertex: string; - logdepthbuf_vertex: string; - map_fragment: string; - map_pars_fragment: string; - map_particle_fragment: string; - map_particle_pars_fragment: string; - morphnormal_vertex: string; - morphtarget_pars_vertex: string; - morphtarget_vertex: string; - normal_phong_fragment: string; - normalmap_pars_fragment: string; - project_vertex: string; - shadowmap_fragment: string; - shadowmap_pars_fragment: string; - shadowmap_pars_vertex: string; - shadowmap_vertex: string; - skinbase_vertex: string; - skinning_pars_vertex: string; - skinning_vertex: string; - skinnormal_vertex: string; - specularmap_fragment: string; - specularmap_pars_fragment: string; - uv2_pars_fragment: string; - uv2_pars_vertex: string; - uv2_vertex: string; - uv_pars_fragment: string; - uv_pars_vertex: string; - uv_vertex: string; - worldpos_vertex: string; - } - - export var ShaderChunk: ShaderChunk; - - export interface Shader { - uniforms: any; - vertexShader: string; - fragmentShader: string; - } - - export var ShaderLib: { - [name: string]: Shader; - basic: Shader; - lambert: Shader; - phong: Shader; - particle_basic: Shader; - dashed: Shader; - depth: Shader; - normal: Shader; - normalmap: Shader; - cube: Shader; - equirect: Shader; - depthRGBA: Shader; - }; - - export var UniformsLib: { - common: any; - aomap: any; - lightmap: any; - emissivemap: any; - bumpmap: any; - normalmap: any; - displacementmap: any; - fog: any; - lights: any; - points: any; - shadowmap: any; - }; - - export var UniformsUtils: { - merge(uniforms: any[]): any; - clone(uniforms_src: any): any; - }; - - // Renderers / WebGL ///////////////////////////////////////////////////////////////////// - export class WebGLBufferRenderer{ - constructor(_gl: any, extensions: any, _infoRender: any); // WebGLRenderingContext - - setMode( value: any ): void; - render( start: any, count: any ): void; - renderInstances( geometry: any ): void; - } - - export class WebGLCapabilities{ - constructor(gl: any, extensions: any, parameters: any); // WebGLRenderingContext - - getMaxPrecision: any; - precision: any; - maxTextures: any; - maxVertexTextures: any; - maxTextureSize: any; - maxCubemapSize: any; - maxAttributes: any; - maxVertexUniforms: any; - maxVaryings: any; - maxFragmentUniforms: any; - vertexTextures: any; - floatFragmentTextures: any; - floatVertexTextures: any; - } - - export class WebGLExtensions{ - constructor(gl: any); // WebGLRenderingContext - - get(name: string): any; - } - - interface WebGLGeometriesInstance { - get( object: any ): any; - } - interface WebGLGeometriesStatic{ - new (gl: any, properties: any, info: any): WebGLGeometriesInstance; - } - export var WebGLGeometries: WebGLGeometriesStatic; - - - interface WebGLIndexedBufferRendererInstance { - setMode( value: any ): void; - setIndex( index: any ): void; - render( start: any, count: any ): void; - renderInstances( geometry: any ): void; - } - interface WebGLIndexedBufferRendererStatic{ - new (gl: any, properties: any, info: any): WebGLIndexedBufferRendererInstance; - } - export var WebGLIndexedBufferRenderer: WebGLIndexedBufferRendererStatic; - - - interface WebGLObjectsInstance { - getAttributeBuffer( attribute: any ): any; - getWireframeAttribute(geometry: any): any; - update(object: any): void; - } - interface WebGLObjectsStatic{ - new (gl: any, properties: any, info: any): WebGLObjectsInstance; - } - export var WebGLObjects: WebGLObjectsStatic; - - export class WebGLProgram{ - constructor(renderer: WebGLRenderer, code: string, material: ShaderMaterial, parameters: WebGLRendererParameters); - - getUniforms(): any; - getAttributes(): any; - - /** Deprecated, use getUniforms */ - uniforms: any; - /** Deprecated, use getAttributes */ - attributes: any; - - id: number; - code: string; - usedTimes: number; - program: any; - vertexShader: WebGLShader; - fragmentShader: WebGLShader; - } - - interface WebGLProgramsInstance { - getParameters( material: any, lights: any, fog: any, object: any ): any[]; - getProgramCode( material: any, parameters: any ): any; - acquireProgram( material: any, parameters: any, code: any ): any; - releaseProgram( program: any ): void; - } - interface WebGLProgramsStatic{ - new (renderer: WebGLRenderer, capabilities: any): WebGLProgramsInstance; - } - export var WebGLPrograms: WebGLProgramsStatic; - - interface WebGLPropertiesInstance { - get(object: any): any; - delete(object: any): void; - clear(): void; - } - interface WebGLPropertiesStatic{ - new (): WebGLPropertiesInstance; - } - export var WebGLProperties: WebGLPropertiesStatic; - - export class WebGLShader{ - constructor(gl: any, type: string, string: string); - } - - interface WebGLShadowMapInstance{ - enabled: boolean; - autoUpdate: boolean; - needsUpdate: boolean; - type: ShadowMapType; - cullFace: CullFace; - - render( scene: Scene ): void; - } - interface WebGLShadowMapStatic{ - new ( _renderer: Renderer, _lights: any[], _objects: any[] ): WebGLStateInstance; - } - export var WebGLShadowMap: WebGLShadowMapStatic; - - interface WebGLStateInstance{ - init(): void; - initAttributes(): void; - enableAttribute(attribute: string): void; - enableAttributeAndDivisor( attribute: string, meshPerAttribute: any, extension: any ): void; - disableUnusedAttributes(): void; - enable( id: string ): void; - disable( id: string ): void; - getCompressedTextureFormats(): any; - setBlending( blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number ): void; - setDepthFunc( func: Function): void; - setDepthTest( depthTest: number ): void; - setDepthWrite( depthWrite: number ): void; - setColorWrite( colorWrite: number ): void; - setFlipSided( flipSided: number ): void; - setLineWidth( width: number ): void; - setPolygonOffset(polygonoffset: number, factor: number, units: number): void; - setScissorTest( scissorTest: boolean ): void; - activeTexture( webglSlot: any ): void; - bindTexture( webglType: any, webglTexture: any ): void; - compressedTexImage2D(): void; - texImage2D(): void; - reset(): void; - } - interface WebGLStateStatic{ - new ( gl: any, extensions: any, paramThreeToGL: Function ): WebGLStateInstance; - } - export var WebGLState: WebGLStateStatic; - - - // Renderers / WebGL / Plugins ///////////////////////////////////////////////////////////////////// - export interface RendererPlugin { - init(renderer: WebGLRenderer): void; - render(scene: Scene, camera: Camera, currentWidth: number, currentHeight: number): void; - } - - export class LensFlarePlugin implements RendererPlugin { - constructor(); - - init(renderer: Renderer): void; - render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; - } - - export class SpritePlugin implements RendererPlugin { - constructor(); - - init(renderer: Renderer): void; - render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; - } - - // Scenes ///////////////////////////////////////////////////////////////////// - - export interface IFog { - name:string; - color: Color; - clone():IFog; - } - - - /** - * This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance. - */ - export class Fog implements IFog { - constructor(hex: number, near?: number, far?: number); - - name:string; - - /** - * Fog color. - */ - color: Color; - - /** - * The minimum distance to start applying fog. Objects that are less than 'near' units from the active camera won't be affected by fog. - */ - near: number; - - /** - * The maximum distance at which fog stops being calculated and applied. Objects that are more than 'far' units away from the active camera won't be affected by fog. - * Default is 1000. - */ - far: number; - - clone(): Fog; - } - - /** - * This class contains the parameters that define linear fog, i.e., that grows exponentially denser with the distance. - */ - export class FogExp2 implements IFog { - constructor(hex: number|string, density?: number); - - name: string; - color: Color; - - /** - * Defines how fast the fog will grow dense. - * Default is 0.00025. - */ - density: number; - - clone(): FogExp2; - } - - /** - * Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras. - */ - export class Scene extends Object3D { - constructor(); - - /** - * A fog instance defining the type of fog that affects everything rendered in the scene. Default is null. - */ - fog: IFog; - - /** - * If not null, it will force everything in the scene to be rendered with that material. Default is null. - */ - overrideMaterial: Material; - autoUpdate: boolean; - - copy(source: Scene): Scene; - } - - // Textures ///////////////////////////////////////////////////////////////////// - export class CanvasTexture extends Texture { - constructor( - canvas: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - - needsUpdate: boolean; - } - - export class CompressedTexture extends Texture { - constructor( - mipmaps: ImageData[], - width: number, - height: number, - format?: PixelFormat, - type?: TextureDataType, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - anisotropy?: number - ); - - image: { width: number; height: number; }; - mipmaps: ImageData[]; - flipY: boolean; - generateMipmaps: boolean; - } - - export class CubeTexture extends Texture { - constructor( - images: any[], // HTMLImageElement or HTMLCanvasElement - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - - images: any[]; - - copy(source: CubeTexture): CubeTexture; - } - - export class DataTexture extends Texture { - constructor( - data: ImageData, - width: number, - height: number, - format: PixelFormat, - type: TextureDataType, - mapping: Mapping, - wrapS: Wrapping, - wrapT: Wrapping, - magFilter: TextureFilter, - minFilter: TextureFilter, - anisotropy?: number - ); - - image: { data: ImageData; width: number; height: number; }; - magFilter: TextureFilter; - minFilter: TextureFilter; - flipY: boolean; - generateMipmaps: boolean; - } - - export class Texture { - constructor( - image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - - id: number; - uuid: string; - name: string; - sourceFile: string; - image: any; // HTMLImageElement or ImageData ; - mipmaps: ImageData[]; - mapping: Mapping; - wrapS: Wrapping; - wrapT: Wrapping; - magFilter: TextureFilter; - minFilter: TextureFilter; - anisotropy: number; - format: PixelFormat; - type: TextureDataType; - offset: Vector2; - repeat: Vector2; - generateMipmaps: boolean; - premultiplyAlpha: boolean; - flipY: boolean; - unpackAlignment: number; - version: number; - needsUpdate: boolean; - onUpdate: () => void; - static DEFAULT_IMAGE: any; - static DEFAULT_MAPPING: any; - - clone(): Texture; - copy(source: Texture): Texture; - toJSON(meta: any): any; - dispose(): void; - transformUv( uv: Vector ): void; - - // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; - } - - class VideoTexture extends Texture { - constructor( - video: HTMLVideoElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - - generateMipmaps: boolean; - } - - // Extras ///////////////////////////////////////////////////////////////////// - export var CurveUtils: { - tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; - } - - // deprecated. - export var ImageUtils: { - crossOrigin: string; - - // deprecated. - loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; - - // deprecated. - loadTextureCube(array: string[], mapping?: Mapping, onLoad?: (texture: Texture) => void , onError?: (message: string) => void ): Texture; - - // deprecated. - getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; - - // deprecated. - generateDataTexture(width: number, height: number, color: Color): DataTexture; - }; - - export var SceneUtils: { - createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; - detach(child: Object3D, parent: Object3D, scene: Scene): void; - attach(child: Object3D, scene: Scene, parent: Object3D): void; - }; - - export var ShapeUtils: { - area( contour: number[] ): number; - triangulate( contour: number[], indices: boolean ): number[]; - triangulateShape( contour: number[], holes: any[] ): number[]; - isClockWise( pts: number[] ): boolean; - b2( t: number, p0: number, p1: number, p2: number ): number; - b3( t: number, p0: number, p1: number, p2: number, p3: number ): number; - }; - - // Extras / Audio ///////////////////////////////////////////////////////////////////// - - export class Audio extends Object3D { - constructor(listener: AudioListener); - type: string; - context: AudioContext; - source: AudioBufferSourceNode; - gain: GainNode; - panner: PannerNode; - autoplay: boolean; - startTime: number; - playbackRate: number; - isPlaying: boolean; - - load(file: string): Audio; - play(): void; - pause(): void; - stop(): void; - connect(): void; - disconnect(): void; - setFilter(value: any): void; - getFilter(): any; - setPlaybackRate(value: number): void; - getPlaybackRate(): number; - - setLoop(value: boolean): void; - getLoop(): boolean; - setRefDistance(value: number): void; - getRefDistance(): number; - setRolloffFactor(value: number): void; - getRolloffFactor(): number; - setVolume(value: number): void; - getVolume(): number; - updateMatrixWorld(force?: boolean): void; - } - - export class AudioListener extends Object3D { - constructor(); - - type: string; - context: AudioContext; - - updateMatrixWorld(force?: boolean): void; - } - - // Extras / Core ///////////////////////////////////////////////////////////////////// - - /** - * An extensible curve object which contains methods for interpolation - * class Curve<T extends Vector> - */ - export class Curve { - /** - * Returns a vector for point t of the curve where t is between 0 and 1 - * getPoint(t: number): T; - */ - getPoint(t: number): T; - - /** - * Returns a vector for point at relative position in curve according to arc length - * getPointAt(u: number): T; - */ - getPointAt(u: number):T; - - /** - * Get sequence of points using getPoint( t ) - * getPoints(divisions?: number): T[]; - */ - getPoints(divisions?: number): T[]; - - /** - * Get sequence of equi-spaced points using getPointAt( u ) - * getSpacedPoints(divisions?: number): T[]; - */ - getSpacedPoints(divisions?: number): T[]; - - /** - * Get total curve arc length - */ - getLength(): number; - - /** - * Get list of cumulative segment lengths - */ - getLengths(divisions?: number): number[]; - - /** - * Update the cumlative segment distance cache - */ - updateArcLengths(): void; - - /** - * Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance - */ - getUtoTmapping(u: number, distance: number): number; - - /** - * Returns a unit vector tangent at t. If the subclassed curve do not implement its tangent derivation, 2 points a small delta apart will be used to find its gradient which seems to give a reasonable approximation - * getTangent(t: number): T; - */ - getTangent(t: number): T; - - /** - * Returns tangent at equidistance point u on the curve - * getTangentAt(u: number): T; - */ - getTangentAt(u: number): T; - - static create(constructorFunc: Function, getPointFunc: Function): Function; - } - - export var CurveUtils: { - tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; - }; - - export interface BoundingBox { - minX: number; - minY: number; - minZ?: number; - maxX: number; - maxY: number; - maxZ?: number; - } - - export class CurvePath extends Curve { - constructor(); - - curves: Curve[]; - autoClose: boolean; - - add(curve: Curve): void; - checkConnection(): boolean; - closePath(): void; - getPoint(t: number): T; - getLength(): number; - getCurveLengths(): number[]; - createPointsGeometry(divisions: number): Geometry; - createSpacedPointsGeometry(divisions: number): Geometry; - createGeometry(points: T[]): Geometry; - } - - export enum PathActions { - MOVE_TO, - LINE_TO, - QUADRATIC_CURVE_TO, // Bezier quadratic curve - BEZIER_CURVE_TO, // Bezier cubic curve - CSPLINE_THRU, // Catmull-rom spline - ARC, // Circle - ELLIPSE, - } - - export interface PathAction { - action: PathActions; - args: any; - } - - /** - * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. - */ - export class Path extends CurvePath { - constructor(points?: Vector2[]); - - actions: PathAction[]; - - fromPoints(vectors: Vector2[]): void; - moveTo(x: number, y: number): void; - lineTo(x: number, y: number): void; - quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; - bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; - splineThru(pts: Vector2[]): void; - arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; - ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; - absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; - getSpacedPoints(divisions?: number, closedPath?: boolean): Vector2[]; - getPoints(divisions?: number, closedPath?: boolean): Vector2[]; - toShapes(): Shape[]; - } - - /** - * Defines a 2d shape plane using paths. - */ - export class Shape extends Path { - constructor(points?: Vector2[]); - - holes: Path[]; - - extrude(options?: any): ExtrudeGeometry; - makeGeometry(options?: any): ShapeGeometry; - getPointsHoles(divisions: number): Vector2[][]; - extractAllPoints(divisions: number): { - shape: Vector2[]; - holes: Vector2[][]; - }; - extractPoints(divisions: number): Vector2[]; - - } - - // Extras / Curves ///////////////////////////////////////////////////////////////////// - export class ArcCurve extends EllipseCurve { - constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); - } - - export class CatmullRomCurve3 extends Curve { - constructor(); - } - - export class ClosedSplineCurve3 extends Curve { - constructor(points?: Vector3[]); - - points: Vector3[]; - } - - export class CubicBezierCurve extends Curve { - constructor(v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2); - - v0: Vector2; - v1: Vector2; - v2: Vector2; - v3: Vector2; - } - export class CubicBezierCurve3 extends Curve { - constructor(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3); - - v0: Vector3; - v1: Vector3; - v2: Vector3; - v3: Vector3; - } - export class EllipseCurve extends Curve { - constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number); - - aX: number; - aY: number; - xRadius: number; - yRadius: number; - aStartAngle: number; - aEndAngle: number; - aClockwise: boolean; - aRotation: number; - } - export class LineCurve extends Curve { - constructor( v1: Vector2, v2: Vector2 ); - - v1: Vector2; - v2: Vector2; - - } - export class LineCurve3 extends Curve { - constructor( v1: Vector3, v2: Vector3 ); - - v1: Vector3; - v2: Vector3; - } - export class QuadraticBezierCurve extends Curve { - constructor( v0: Vector2, v1: Vector2, v2: Vector2 ); - - v0: Vector2; - v1: Vector2; - v2: Vector2; - } - export class QuadraticBezierCurve3 extends Curve { - constructor( v0: Vector3, v1: Vector3, v2: Vector3 ); - - v0: Vector3; - v1: Vector3; - v2: Vector3; - } - export class SplineCurve extends Curve { - constructor( points?: Vector2[] ); - - points:Vector2[]; - } - export class SplineCurve3 extends Curve { - constructor( points?: Vector3[] ); - - points:Vector3[]; - } - - // Extras / Geomerties ///////////////////////////////////////////////////////////////////// - /** - * BoxGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. - */ - export class BoxGeometry extends Geometry { - /** - * @param width — Width of the sides on the X axis. - * @param height — Height of the sides on the Y axis. - * @param depth — Depth of the sides on the Z axis. - * @param widthSegments — Number of segmented faces along the width of the sides. - * @param heightSegments — Number of segmented faces along the height of the sides. - * @param depthSegments — Number of segmented faces along the depth of the sides. - */ - constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); - - parameters: { - width: number; - height: number; - depth: number; - widthSegments: number; - heightSegments: number; - depthSegments: number; - }; - - clone(): BoxGeometry; - } - - export class CircleBufferGeometry extends Geometry { - constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); - - parameters: { - radius: number; - segments: number; - thetaStart: number; - thetaLength: number; - }; - - clone(): CircleBufferGeometry; - } - - export class CircleGeometry extends Geometry { - constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); - - parameters: { - radius: number; - segments: number; - thetaStart: number; - thetaLength: number; - }; - - clone(): CircleGeometry; - } - - // deprecated - export class CubeGeometry extends BoxGeometry { - } - - export class CylinderGeometry extends Geometry { - /** - * @param radiusTop — Radius of the cylinder at the top. - * @param radiusBottom — Radius of the cylinder at the bottom. - * @param height — Height of the cylinder. - * @param radiusSegments — Number of segmented faces around the circumference of the cylinder. - * @param heightSegments — Number of rows of faces along the height of the cylinder. - * @param openEnded - A Boolean indicating whether or not to cap the ends of the cylinder. - */ - constructor(radiusTop?: number, radiusBottom?: number, height?: number, radiusSegments?: number, heightSegments?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number); - - parameters: { - radiusTop: number; - radiusBottom: number; - height: number; - radialSegments: number; - heightSegments: number; - openEnded: boolean; - thetaStart: number; - thetaLength: number; - }; - - clone(): CylinderGeometry; - } - - export class DodecahedronGeometry extends Geometry { - constructor(radius: number, detail: number); - - parameters: { - radius: number; - detail: number; - }; - - clone(): DodecahedronGeometry; - } - - export class EdgesGeometry extends BufferGeometry { - constructor(geometry: BufferGeometry, thresholdAngle: number); - - clone(): EdgesGeometry; - } - - export class ExtrudeGeometry extends Geometry { - constructor(shape?: Shape, options?: any); - constructor(shapes?: Shape[], options?: any); - - static WorldUVGenerator: { - generateTopUV(geometry: Geometry, indexA: number, indexB: number, indexC: number): Vector2[]; - generateSideWallUV(geometry: Geometry, indexA: number, indexB: number, indexC: number, indexD: number): Vector2[]; - }; - - addShapeList(shapes: Shape[], options?: any): void; - addShape(shape: Shape, options?: any): void; - } - - export class IcosahedronGeometry extends PolyhedronGeometry { - constructor(radius: number, detail: number); - - clone(): IcosahedronGeometry; - } - - export class LatheGeometry extends Geometry { - constructor(points: Vector3[], segments?: number, phiStart?: number, phiLength?: number); - - parameters: { - points: Vector3[]; - segments: number; - phiStart: number; - phiLength: number; - }; - } - - export class OctahedronGeometry extends PolyhedronGeometry { - constructor(radius: number, detail: number); - - clone(): OctahedronGeometry; - } - - export class ParametricGeometry extends Geometry { - constructor(func: (u: number, v: number) => Vector3, slices: number, stacks: number); - - parameters: { - func: (u: number, v: number) => Vector3; - slices: number; - stacks: number; - }; - } - - export class PlaneBufferGeometry extends BufferGeometry { - constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); - - parameters: { - width: number; - height: number; - widthSegments: number; - heightSegments: number; - }; - - clone(): PlaneBufferGeometry; - } - - export class PlaneGeometry extends Geometry { - constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); - - parameters: { - width: number; - height: number; - widthSegments: number; - heightSegments: number; - }; - - clone(): PlaneGeometry; - } - - export class PolyhedronGeometry extends Geometry { - constructor(vertices: Vector3[], faces: Face3[], radius?: number, detail?: number); - - parameters: { - vertices: Vector3[]; - faces: Face3[]; - radius: number; - detail: number; - }; - - clone(): PolyhedronGeometry; - } - - export class RingGeometry extends Geometry { - constructor(innerRadius?: number, outerRadius?: number, thetaSegments?: number, phiSegments?: number, thetaStart?: number, thetaLength?: number); - - parameters: { - innerRadius: number; - outerRadius: number; - thetaSegments: number; - phiSegments: number; - thetaStart: number; - thetaLength: number; - }; - - clone(): RingGeometry; - } - - export class ShapeGeometry extends Geometry { - constructor(shape: Shape, options?: any); - constructor(shapes: Shape[], options?: any); - - - addShapeList(shapes: Shape[], options: any): ShapeGeometry; - addShape(shape: Shape, options?: any): void; - } - - - export class SphereBufferGeometry extends BufferGeometry { - constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); - - parameters: { - radius: number; - widthSegments: number; - heightSegments: number; - phiStart: number; - phiLength: number; - thetaStart: number; - thetaLength: number; - }; - - clone(): SphereBufferGeometry; - } - - /** - * A class for generating sphere geometries - */ - export class SphereGeometry extends Geometry { - /** - * The geometry is created by sweeping and calculating vertexes around the Y axis (horizontal sweep) and the Z axis (vertical sweep). Thus, incomplete spheres (akin to 'sphere slices') can be created through the use of different values of phiStart, phiLength, thetaStart and thetaLength, in order to define the points in which we start (or end) calculating those vertices. - * - * @param radius — sphere radius. Default is 50. - * @param widthSegments — number of horizontal segments. Minimum value is 3, and the default is 8. - * @param heightSegments — number of vertical segments. Minimum value is 2, and the default is 6. - * @param phiStart — specify horizontal starting angle. Default is 0. - * @param phiLength — specify horizontal sweep angle size. Default is Math.PI * 2. - * @param thetaStart — specify vertical starting angle. Default is 0. - * @param thetaLength — specify vertical sweep angle size. Default is Math.PI. - */ - constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); - - parameters: { - radius: number; - widthSegments: number; - heightSegments: number; - phiStart: number; - phiLength: number; - thetaStart: number; - thetaLength: number; - }; - } - - export class TetrahedronGeometry extends PolyhedronGeometry { - constructor(radius?: number, detail?: number); - - clone(): TetrahedronGeometry; - } - - export class TorusGeometry extends Geometry { - constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, arc?: number); - - parameters: { - radius: number; - tube: number; - radialSegments: number; - tubularSegments: number; - arc: number; - }; - - clone(): TorusGeometry; - } - - export class TorusKnotGeometry extends Geometry { - constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, heightScale?: number); - - parameters: { - radius: number; - tube: number; - radialSegments: number; - tubularSegments: number; - p: number; - q: number; - heightScale: number; - }; - - clone(): TorusKnotGeometry; - } - - - export class TubeGeometry extends Geometry { - constructor(path: Path, segments?: number, radius?: number, radiusSegments?: number, closed?: boolean, taper?: (u: number) => number); - - parameters: { - path: Path; - segments: number; - radius: number; - radialSegments: number; - closed: boolean; - taper: (u: number) => number; // NoTaper or SinusoidalTaper; - }; - tangents: Vector3[]; - normals: Vector3[]; - binormals: Vector3[]; - - static NoTaper(u?: number): number; - static SinusoidalTaper(u: number): number; - static FrenetFrames(path: Path, segments: number, closed: boolean): void; - - clone(): TubeGeometry; - } - - export class WireframeGeometry extends BufferGeometry{ - constructor(geometry: Geometry | BufferGeometry); - } - - // Extras / Helpers ///////////////////////////////////////////////////////////////////// - - export class ArrowHelper extends Object3D { - constructor(dir: Vector3, origin?: Vector3, length?: number, hex?: number, headLength?: number, headWidth?: number); - - line: Line; - cone: Mesh; - - setDirection(dir: Vector3): void; - setLength(length: number, headLength?: number, headWidth?: number): void; - setColor(hex: number): void; - } - - export class AxisHelper extends LineSegments { - constructor(size?: number); - } - - export class BoundingBoxHelper extends Mesh { - constructor(object?: Object3D, hex?: number); - - object: Object3D; - box: Box3; - - update(): void; - } - - export class BoxHelper extends LineSegments { - constructor(object?: Object3D); - - update(object?: Object3D): void; - } - - export class CameraHelper extends LineSegments { - constructor(camera: Camera); - - camera: Camera; - pointMap: { [id: string]: number[]; }; - - update(): void; - } - - export class DirectionalLightHelper extends Object3D { - constructor(light: Light, size?: number); - - light: Light; - lightPlane: Line; - targetLine: Line; - - dispose(): void; - update(): void; - } - - export class EdgesHelper extends LineSegments { - constructor(object: Object3D, hex?: number, thresholdAngle?: number); - - } - - export class FaceNormalsHelper extends LineSegments { - constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); - - object: Object3D; - size: number; - - update(object?: Object3D): void; - } - - export class GridHelper extends LineSegments { - constructor(size: number, step: number); - - color1: Color; - color2: Color; - - setColors(colorCenterLine: number, colorGrid: number): void; - } - export class HemisphereLightHelper extends Object3D { - constructor(light: Light, sphereSize: number); - - light: Light; - colors: Color[]; - lightSphere: Mesh; - - dispose(): void; - update(): void; - } - - export class PointLightHelper extends Object3D { - constructor(light: Light, sphereSize: number); - - light: Light; - - dispose(): void; - update(): void; - } - - export class SkeletonHelper extends LineSegments { - constructor(bone: Object3D); - - bones: Bone[]; - root: Object3D; - - getBoneList(object: Object3D): Bone[]; - update(): void; - } - - export class SpotLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number); - - light: Light; - cone: Mesh; - - dispose(): void; - update(): void; - } - - export class VertexNormalsHelper extends LineSegments { - constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); - - object: Object3D; - size: number; - - update(object?: Object3D): void; - } - - export class WireframeHelper extends LineSegments { - constructor(object: Object3D, hex?: number); - - } - - // Extras / Objects ///////////////////////////////////////////////////////////////////// - - export class ImmediateRenderObject extends Object3D { - constructor(material: Material); - - material: Material; - render(renderCallback:Function): void; - } - - export interface MorphBlendMeshAnimation { - start: number; - end: number; - length: number; - fps: number; - duration: number; - lastFrame: number; - currentFrame: number; - active: boolean; - time: number; - direction: number; - weight: number; - directionBackwards: boolean; - mirroredLoop: boolean; - } - - export class MorphBlendMesh extends Mesh { - constructor(geometry: Geometry, material: Material); - - animationsMap: { [name: string]: MorphBlendMeshAnimation; }; - animationsList: MorphBlendMeshAnimation[]; - - createAnimation(name: string, start: number, end: number, fps: number): void; - autoCreateAnimations(fps: number): void; - setAnimationDirectionForward(name: string): void; - setAnimationDirectionBackward(name: string): void; - setAnimationFPS(name: string, fps: number): void; - setAnimationDuration(name: string, duration: number): void; - setAnimationWeight(name: string, weight: number): void; - setAnimationTime(name: string, time: number): void; - getAnimationTime(name: string): number; - getAnimationDuration(name: string): number; - playAnimation(name: string): void; - stopAnimation(name: string): void; - update(delta: number): void; - } -} - -declare module 'three' { - export = THREE; -} +// Type definitions for three.js r73 +// Project: http://mrdoob.github.com/three.js/ +// Definitions by: Kon , Satoru Kimura +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module THREE { + export var REVISION: string; + + // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button + export enum MOUSE { LEFT, MIDDLE, RIGHT } + + // GL STATE CONSTANTS + export enum CullFace { } + export var CullFaceNone: CullFace; + export var CullFaceBack: CullFace; + export var CullFaceFront: CullFace; + export var CullFaceFrontBack: CullFace; + + export enum FrontFaceDirection { } + export var FrontFaceDirectionCW: FrontFaceDirection; + export var FrontFaceDirectionCCW: FrontFaceDirection; + + // Shadowing Type + export enum ShadowMapType { } + export var BasicShadowMap: ShadowMapType; + export var PCFShadowMap: ShadowMapType; + export var PCFSoftShadowMap: ShadowMapType; + + // MATERIAL CONSTANTS + + // side + export enum Side { } + export var FrontSide: Side; + export var BackSide: Side; + export var DoubleSide: Side; + + // shading + export enum Shading { } + export var NoShading: Shading; + export var FlatShading: Shading; + export var SmoothShading: Shading; + + // colors + export enum Colors { } + export var NoColors: Colors; + export var FaceColors: Colors; + export var VertexColors: Colors; + + // blending modes + export enum Blending { } + export var NoBlending: Blending; + export var NormalBlending: Blending; + export var AdditiveBlending: Blending; + export var SubtractiveBlending: Blending; + export var MultiplyBlending: Blending; + export var CustomBlending: Blending; + + // custom blending equations + // (numbers start from 100 not to clash with other + // mappings to OpenGL constants defined in Texture.js) + export enum BlendingEquation { } + export var AddEquation: BlendingEquation; + export var SubtractEquation: BlendingEquation; + export var ReverseSubtractEquation: BlendingEquation; + export var MinEquation: BlendingEquation; + export var MaxEquation: BlendingEquation; + + // custom blending destination factors + export enum BlendingDstFactor { } + export var ZeroFactor: BlendingDstFactor; + export var OneFactor: BlendingDstFactor; + export var SrcColorFactor: BlendingDstFactor; + export var OneMinusSrcColorFactor: BlendingDstFactor; + export var SrcAlphaFactor: BlendingDstFactor; + export var OneMinusSrcAlphaFactor: BlendingDstFactor; + export var DstAlphaFactor: BlendingDstFactor; + export var OneMinusDstAlphaFactor: BlendingDstFactor; + + // custom blending src factors + export enum BlendingSrcFactor { } + export var DstColorFactor: BlendingSrcFactor; + export var OneMinusDstColorFactor: BlendingSrcFactor; + export var SrcAlphaSaturateFactor: BlendingSrcFactor; + + // depth modes + export enum DepthModes { } + export var NeverDepth: DepthModes; + export var AlwaysDepth: DepthModes; + export var LessDepth: DepthModes; + export var LessEqualDepth: DepthModes; + export var EqualDepth: DepthModes; + export var GreaterEqualDepth: DepthModes; + export var GreaterDepth: DepthModes; + export var NotEqualDepth: DepthModes; + + // TEXTURE CONSTANTS + // Operations + export enum Combine { } + export var MultiplyOperation: Combine; + export var MixOperation: Combine; + export var AddOperation: Combine; + + // Mapping modes + export enum Mapping { } + export var UVMapping: Mapping; + export var CubeReflectionMapping: Mapping; + export var CubeRefractionMapping: Mapping; + export var EquirectangularReflectionMapping: Mapping; + export var EquirectangularRefractionMapping: Mapping; + export var SphericalReflectionMapping: Mapping; + + // Wrapping modes + export enum Wrapping { } + export var RepeatWrapping: Wrapping; + export var ClampToEdgeWrapping: Wrapping; + export var MirroredRepeatWrapping: Wrapping; + + // Filters + export enum TextureFilter { } + export var NearestFilter: TextureFilter; + export var NearestMipMapNearestFilter: TextureFilter; + export var NearestMipMapLinearFilter: TextureFilter; + export var LinearFilter: TextureFilter; + export var LinearMipMapNearestFilter: TextureFilter; + export var LinearMipMapLinearFilter: TextureFilter; + + // Data types + export enum TextureDataType { } + export var UnsignedByteType: TextureDataType; + export var ByteType: TextureDataType; + export var ShortType: TextureDataType; + export var UnsignedShortType: TextureDataType; + export var IntType: TextureDataType; + export var UnsignedIntType: TextureDataType; + export var FloatType: TextureDataType; + export var HalfFloatType: TextureDataType; + + // Pixel types + export enum PixelType { } + export var UnsignedShort4444Type: PixelType; + export var UnsignedShort5551Type: PixelType; + export var UnsignedShort565Type: PixelType; + + // Pixel formats + export enum PixelFormat { } + export var AlphaFormat: PixelFormat; + export var RGBFormat: PixelFormat; + export var RGBAFormat: PixelFormat; + export var LuminanceFormat: PixelFormat; + export var LuminanceAlphaFormat: PixelFormat; + export var RGBEFormat: PixelFormat; + + // Compressed texture formats + // DDS / ST3C Compressed texture formats + export enum CompressedPixelFormat { } + export var RGB_S3TC_DXT1_Format: CompressedPixelFormat; + export var RGBA_S3TC_DXT1_Format: CompressedPixelFormat; + export var RGBA_S3TC_DXT3_Format: CompressedPixelFormat; + export var RGBA_S3TC_DXT5_Format: CompressedPixelFormat; + + // PVRTC compressed texture formats + export var RGB_PVRTC_4BPPV1_Format: CompressedPixelFormat; + export var RGB_PVRTC_2BPPV1_Format: CompressedPixelFormat; + export var RGBA_PVRTC_4BPPV1_Format: CompressedPixelFormat; + export var RGBA_PVRTC_2BPPV1_Format: CompressedPixelFormat; + + // Loop styles for AnimationAction + export enum AnimationActionLoopStyles { } + export var LoopOnce: AnimationActionLoopStyles; + export var LoopRepeat: AnimationActionLoopStyles; + export var LoopPingPong: AnimationActionLoopStyles; + + // log handlers + export function warn(message?: any, ...optionalParams: any[]): void; + export function error(message?: any, ...optionalParams: any[]): void; + export function log(message?: any, ...optionalParams: any[]): void; + + // Animation //////////////////////////////////////////////////////////////////////////////////////// + export class AnimationAction { + constructor(clip: AnimationClip, startTime?: number, timeScale?: number, weight?: number, loop?: boolean); + + clip: AnimationClip + localRoot: Mesh; + startTime: number; + timeScale: number; + weight: number; + loop: AnimationActionLoopStyles; + loopCount: number; + enabled: boolean; + actionTime: number; + clipTime: number; + propertyBindings: PropertyBinding[]; + + setLocalRoot( localRoot: Mesh ): AnimationAction; + updateTime( clipDeltaTime: number ): number; + syncWith( action: AnimationAction ): AnimationAction; + warpToDuration( duration: number ): AnimationAction; + init( time: number ): AnimationAction; + update( clipDeltaTime: number ): any[]; + getTimeScaleAt( time: number ): number; + getWeightAt( time: number ): number; + } + + export class AnimationClip { + constructor( name: string, duration?: number, tracks?: KeyframeTrack[] ); + + name: string; + tracks: KeyframeTrack[]; + duration: number; + results: any[]; + + getAt(clipTime: number): any[]; + trim(): AnimationClip; + optimize(): AnimationClip; + + static CreateFromMorphTargetSequence( name: string, morphTargetSequence: MorphTarget[], fps: number ): AnimationClip; + findByName( clipArray: AnimationClip, name: string ): AnimationClip; + static CreateClipsFromMorphTargetSequences( morphTargets: MorphTarget[], fps: number ): AnimationClip[]; + parse( json: any ): AnimationClip; + parseAnimation( animation: any, bones: Bone[], nodeName: string ): AnimationClip; + } + + export class AnimationMixer { + constructor( root: any ); + + root: any; + time: number; + timeScale: number; + actions: AnimationAction; + propertyBindingMap: any; + + addAction( action: AnimationAction ): void; + removeAllActions(): AnimationMixer; + removeAction( action: AnimationAction ): AnimationMixer; + findActionByName( name: string ): AnimationAction; + play( action: AnimationAction, optionalFadeInDuration?: number ): AnimationMixer; + fadeOut( action: AnimationAction, duration: number ): AnimationMixer; + fadeIn( action: AnimationAction, duration: number ): AnimationMixer; + warp( action: AnimationAction, startTimeScale: NumberKeyframeTrack, endTimeScale: NumberKeyframeTrack, duration: number ): AnimationMixer; + crossFade( fadeOutAction: AnimationAction, fadeInAction: AnimationAction, duration: number, warp: boolean ): AnimationMixer; + update( deltaTime: number ): AnimationMixer; + } + + export var AnimationUtils: { + getEqualsFunc( exemplarValue: any ): boolean; + clone(exemplarValue: T): T; + lerp( a: any, b: any, alpha: number, interTrack: boolean ): any; + lerp_object( a: any, b: any, alpha: number ): any; + slerp_object( a: any, b: any, alpha: number ): any; + lerp_number( a: any, b: any, alpha: number ): any; + lerp_boolean( a: any, b: any, alpha: number ): any; + lerp_boolean_immediate( a: any, b: any, alpha: number ): any; + lerp_string( a: any, b: any, alpha: number ): any; + lerp_string_immediate( a: any, b: any, alpha: number ): any; + getLerpFunc( exemplarValue: any, interTrack: boolean ): Function; + }; + + export class KeyframeTrack { + constructor(name: string, keys: any[]); + + name: string; + keys: any[]; + lastIndex: number; + + getAt( time: number ): any; + shift( timeOffset: number ): KeyframeTrack; + scale( timeScale: number ): KeyframeTrack; + trim( startTime: number, endTime: number ): KeyframeTrack; + validate(): KeyframeTrack; + optimize(): KeyframeTrack; + + keyComparator(key0: KeyframeTrack, key1: KeyframeTrack): number; + parse( json: any ): KeyframeTrack; + GetTrackTypeForTypeName( typeName: string ): any; + } + + export class PropertyBinding { + constructor( rootNode: any, trackName: string ); + + rootNode: any; + trackName: string; + referenceCount: number; + originalValue: any; + directoryName: string; + nodeName: string; + objectName: string; + objectIndex: number; + propertyName: string; + propertyIndex: number; + node: any; + cumulativeValue: number; + cumulativeWeight: number; + + reset(): void; + accumulate( value: any, weight: number ): void; + unbind(): void; + bind(): void; + apply(): void; + parseTrackName( trackName: string ): any; + findNode( root: any, nodeName: string ): any; + } + + export class BooleanKeyframeTrack extends KeyframeTrack { + constructor(name: string, keys: any[]); + + result: any; + + setResult( value: any ): void; + lerpValues( value0: any, value1: any, alpha: number ): any; + compareValues( value0: any, value1: any ): boolean; + clone(): BooleanKeyframeTrack; + parse( json: any ): BooleanKeyframeTrack; + } + + export class NumberKeyframeTrack { + constructor(); + + result: any; + + setResult( value: any ): void; + lerpValues( value0: any, value1: any, alpha: number ): any; + compareValues( value0: any, value1: any ): boolean; + clone(): NumberKeyframeTrack; + parse( json: any ): NumberKeyframeTrack; + } + + export class QuaternionKeyframeTrack { + constructor(); + + result: any; + + setResult( value: any ): void; + lerpValues( value0: any, value1: any, alpha: number ): any; + compareValues( value0: any, value1: any ): boolean; + clone(): QuaternionKeyframeTrack; + parse( json: any ): QuaternionKeyframeTrack; + } + + export class StringKeyframeTrack { + constructor(); + + result: any; + + setResult( value: any ): void; + lerpValues( value0: any, value1: any, alpha: number ): any; + compareValues( value0: any, value1: any ): boolean; + clone(): StringKeyframeTrack; + parse( json: any ): StringKeyframeTrack; + } + + export class VectorKeyframeTrack { + constructor(); + + result: any; + + setResult( value: any ): void; + lerpValues( value0: any, value1: any, alpha: number ): any; + compareValues( value0: any, value1: any ): boolean; + clone(): VectorKeyframeTrack; + parse( json: any ): VectorKeyframeTrack; + } + + // Cameras //////////////////////////////////////////////////////////////////////////////////////// + + /** + * Abstract base class for cameras. This class should always be inherited when you build a new camera. + */ + export class Camera extends Object3D { + /** + * This constructor sets following properties to the correct type: matrixWorldInverse, projectionMatrix and projectionMatrixInverse. + */ + constructor(); + + /** + * This is the inverse of matrixWorld. MatrixWorld contains the Matrix which has the world transform of the Camera. + */ + matrixWorldInverse: Matrix4; + + /** + * This is the matrix which contains the projection. + */ + projectionMatrix: Matrix4; + + getWorldDirection(optionalTarget?: Vector3): Vector3; + + /** + * This make the camera look at the vector position in local space. + * @param vector point to look at + */ + lookAt(vector: Vector3): void; + + clone(): Camera; + copy(camera?: Camera): Camera; + } + + export class CubeCamera extends Object3D { + constructor( near?: number, far?: number, cubeResolution?: number); + + renderTarget: WebGLRenderTargetCube; + + updateCubeMap( renderer: Renderer, scene: Scene ): void; + + } + + /** + * Camera with orthographic projection + * + * @example + * var camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 ); + * scene.add( camera ); + * + * @see src/cameras/OrthographicCamera.js + */ + export class OrthographicCamera extends Camera { + /** + * @param left Camera frustum left plane. + * @param right Camera frustum right plane. + * @param top Camera frustum top plane. + * @param bottom Camera frustum bottom plane. + * @param near Camera frustum near plane. + * @param far Camera frustum far plane. + */ + constructor(left: number, right: number, top: number, bottom: number, near?: number, far?: number); + + zoom: number; + + /** + * Camera frustum left plane. + */ + left: number; + + /** + * Camera frustum right plane. + */ + right: number; + + /** + * Camera frustum top plane. + */ + top: number; + + /** + * Camera frustum bottom plane. + */ + bottom: number; + + /** + * Camera frustum near plane. + */ + near: number; + + /** + * Camera frustum far plane. + */ + far: number; + + /** + * Updates the camera projection matrix. Must be called after change of parameters. + */ + updateProjectionMatrix(): void; + clone(): OrthographicCamera; + copy( source: OrthographicCamera ): OrthographicCamera; + toJSON( meta?: any ): any; + } + + /** + * Camera with perspective projection. + * + * # example + * var camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 ); + * scene.add( camera ); + * + * @source https://github.com/mrdoob/three.js/blob/master/src/cameras/PerspectiveCamera.js + */ + export class PerspectiveCamera extends Camera { + /** + * @param fov Camera frustum vertical field of view. Default value is 50. + * @param aspect Camera frustum aspect ratio. Default value is 1. + * @param near Camera frustum near plane. Default value is 0.1. + * @param far Camera frustum far plane. Default value is 2000. + */ + constructor(fov?: number, aspect?: number, near?: number, far?: number); + + zoom: number; + + /** + * Camera frustum vertical field of view, from bottom to top of view, in degrees. + */ + fov: number; + + /** + * Camera frustum aspect ratio, window width divided by window height. + */ + aspect: number; + + /** + * Camera frustum near plane. + */ + near: number; + + /** + * Camera frustum far plane. + */ + far: number; + + /** + * Uses focal length (in mm) to estimate and set FOV 35mm (fullframe) camera is used if frame size is not specified. + * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html + * @param focalLength focal length + * @param frameHeight frame size. Default value is 24. + */ + setLens(focalLength: number, frameHeight?: number): void; + + /** + * Sets an offset in a larger frustum. This is useful for multi-window or multi-monitor/multi-machine setups. + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and the monitors are in grid like this: + * + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + * + * then for each monitor you would call it like this: + * + * var w = 1920; + * var h = 1080; + * var fullWidth = w * 3; + * var fullHeight = h * 2; + * + * // A + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * // B + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * // C + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * // D + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * // E + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * // F + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); Note there is no reason monitors have to be the same size or in a grid. + * + * @param fullWidth full width of multiview setup + * @param fullHeight full height of multiview setup + * @param x horizontal offset of subcamera + * @param y vertical offset of subcamera + * @param width width of subcamera + * @param height height of subcamera + */ + setViewOffset(fullWidth: number, fullHeight: number, x: number, y: number, width: number, height: number): void; + + /** + * Updates the camera projection matrix. Must be called after change of parameters. + */ + updateProjectionMatrix(): void; + clone(): PerspectiveCamera; + copy( source: PerspectiveCamera ): PerspectiveCamera; + toJSON( meta?: any ): any; + } + + // Core /////////////////////////////////////////////////////////////////////////////////////////////// + + /** + * @see src/core/BufferAttribute.js + */ + export class BufferAttribute { + constructor(array: ArrayLike, itemSize: number); // array parameter should be TypedArray. + + uuid: string; + array: ArrayLike; + itemSize: number; + dynamic: boolean; + updateRange: {offset:number, count:number}; + version: number; + + needsUpdate: boolean; + /** Deprecated, use count instead */ + length: number; + count: number; + + setDynamic(dynamic: boolean): BufferAttribute; + clone(): BufferAttribute; + copy(source: BufferAttribute): BufferAttribute; + copyAt(index1: number, attribute: BufferAttribute, index2: number): BufferAttribute; + copyArray(array: ArrayLike): BufferAttribute; + copyColorsArray(colors: {r:number, g:number, b:number}[]): BufferAttribute; + copyIndicesArray(indices: {a:number, b:number, c:number}[]): BufferAttribute; + copyVector2sArray(vectors: {x:number, y:number}[]): BufferAttribute; + copyVector3sArray(vectors: {x:number, y:number, z:number}[]): BufferAttribute; + copyVector4sArray(vectors: {x:number, y:number, z:number, w:number}[]): BufferAttribute; + set(value: ArrayLike, offset?: number): BufferAttribute; + getX(index: number): number; + setX(index: number, x: number): BufferAttribute; + getY(index: number): number; + setY(index: number, y: number): BufferAttribute; + getZ(index: number): number; + setZ(index: number, z: number): BufferAttribute; + getW(index: number): number; + setW(index: number, z: number): BufferAttribute; + setXY(index: number, x: number, y: number): BufferAttribute; + setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; + setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; + clone(): BufferAttribute; + } + + // deprecated (are these actually deprecated?) + export class Int8Attribute extends BufferAttribute{ + constructor(array: any, itemSize: number); + } + + // deprecated + export class Uint8Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Uint8ClampedAttribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Int16Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Uint16Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Int32Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Uint32Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Float32Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + // deprecated + export class Float64Attribute extends BufferAttribute { + constructor(array: any, itemSize: number); + } + + /** + * This is a superefficent class for geometries because it saves all data in buffers. + * It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the nessecary buffer calculations. + * It is mainly interesting when working with static objects. + * + * @see src/core/BufferGeometry.js + */ + export class BufferGeometry { + /** + * This creates a new BufferGeometry. It also sets several properties to an default value. + */ + constructor(); + + static MaxIndex: number; + + /** + * Unique number of this buffergeometry instance + */ + id: number; + uuid: string; + name: string; + type: string; + index: BufferAttribute; + attributes: BufferAttribute|InterleavedBufferAttribute[]; + morphAttributes: any; + groups: {start: number, count: number, materialIndex?: number}[]; + boundingBox: Box3; + boundingSphere: BoundingSphere; + drawRange: { start: number, count: number }; + + /** Deprecated. */ + addIndex( index: BufferAttribute ): void; + + getIndex(): BufferAttribute; + setIndex( index: BufferAttribute ): void; + + /** Deprecated. This overloaded method is deprecated. */ + addAttribute(name: string, array: any, itemSize: number): any; + addAttribute(name: string, attribute: BufferAttribute|InterleavedBufferAttribute): void; + getAttribute(name: string): BufferAttribute|InterleavedBufferAttribute; + removeAttribute(name: string): void; + + /** Deprecated. */ + drawcalls(): any; + /** Deprecated. */ + offsets(): any; + + /** Deprecated. Use addGroup */ + addDrawCall(start: number, count: number, index?: number): void; + /** Deprecated. */ + clearDrawCalls(): void; + addGroup(start: number, count: number, materialIndex?: number): void; + clearGroups(): void; + + setDrawRange(start: number, count: number): void; + + /** + * Bakes matrix transform directly into vertex coordinates. + */ + applyMatrix(matrix: Matrix4): void; + + rotateX(angle: number): BufferGeometry; + rotateY(angle: number): BufferGeometry; + rotateZ(angle: number): BufferGeometry; + translate(x: number, y: number, z: number): BufferGeometry; + scale(x: number, y: number, z: number): BufferGeometry; + lookAt(v: Vector3): void; + + center(): Vector3; + + setFromObject(object: Object3D) : void; + updateFromObject(object: Object3D) : void; + + fromGeometry(geometry: Geometry, settings?: any): BufferGeometry; + + fromDirectGeometry( geometry: DirectGeometry ): BufferGeometry; + + /** + * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. + * Bounding boxes aren't computed by default. They need to be explicitly computed, otherwise they are null. + */ + computeBoundingBox(): void; + + /** + * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. + * Bounding spheres aren't' computed by default. They need to be explicitly computed, otherwise they are null. + */ + computeBoundingSphere(): void; + + // deprecated + computeFaceNormals(): void; + + /** + * Computes vertex normals by averaging face normals. + */ + computeVertexNormals(): void; + + computeOffsets(size: number): void; + merge(geometry: BufferGeometry, offset: number): BufferGeometry; + normalizeNormals(): void; + toJSON(): any; + clone(): BufferGeometry; + copy(source: BufferGeometry): BufferGeometry; + + /** + * Disposes the object from memory. + * You need to call this when you want the bufferGeometry removed while the application is running. + */ + dispose(): void; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } + + export class Channels { + constructor(); + + mask: number; + + set( channel: number ): void; + enable( channel: number ): void; + toggle( channel: number ): void; + disable( channel: number ): void; + } + + /** + * Object for keeping track of time. + * + * @see src/core/Clock.js + */ + export class Clock { + /** + * @param autoStart Automatically start the clock. + */ + constructor(autoStart?: boolean); + + /** + * If set, starts the clock automatically when the first update is called. + */ + autoStart: boolean; + + /** + * When the clock is running, It holds the starttime of the clock. + * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + */ + startTime: number; + + /** + * When the clock is running, It holds the previous time from a update. + * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + */ + oldTime: number; + + /** + * When the clock is running, It holds the time elapsed between the start of the clock to the previous update. + * This parameter is in seconds of three decimal places. + */ + elapsedTime: number; + + /** + * This property keeps track whether the clock is running or not. + */ + running: boolean; + + /** + * Starts clock. + */ + start(): void; + + /** + * Stops clock. + */ + stop(): void; + + /** + * Get the seconds passed since the clock started. + */ + getElapsedTime(): number; + + /** + * Get the seconds passed since the last call to this method. + */ + getDelta(): number; + } + + /** + * @see src/core/DirectGeometry.js + */ + export class DirectGeometry { + constructor(); + + id: number; + uuid: string; + name: string; + type: string; + indices: number[]; + vertices: Vector3[]; + normals: Vector3[]; + colors: Color[]; + uvs: Vector2[]; + uvs2: Vector2[]; + groups: {start: number, materialIndex: number}[]; + morphTargets: MorphTarget[]; + skinWeights: number[]; + skinIndices: number[]; + boundingBox: Box3; + boundingSphere: BoundingSphere; + verticesNeedUpdate: boolean; + normalsNeedUpdate: boolean; + colorsNeedUpdate: boolean; + uvsNeedUpdate: boolean; + groupsNeedUpdate: boolean; + + computeBoundingBox(): void; + computeBoundingSphere(): void; + computeGroups(geometry: Geometry): void; + fromGeometry(geometry: Geometry): DirectGeometry; + dispose(): void; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } + + /** + * JavaScript events for custom objects + * + * # Example + * var Car = function () { + * + * EventDispatcher.call( this ); + * this.start = function () { + * + * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } ); + * + * }; + * + * }; + * + * var car = new Car(); + * car.addEventListener( 'start', function ( event ) { + * + * alert( event.message ); + * + * } ); + * car.start(); + * + * @source src/core/EventDispatcher.js + */ + export class EventDispatcher { + /** + * Creates eventDispatcher object. It needs to be call with '.call' to add the functionality to an object. + */ + constructor(); + + /** + * Adds a listener to an event type. + * @param type The type of the listener that gets removed. + * @param listener The listener function that gets removed. + */ + addEventListener(type: string, listener: (event: any) => void ): void; + + /** + * Adds a listener to an event type. + * @param type The type of the listener that gets removed. + * @param listener The listener function that gets removed. + */ + hasEventListener(type: string, listener: (event: any) => void): void; + + /** + * Removes a listener from an event type. + * @param type The type of the listener that gets removed. + * @param listener The listener function that gets removed. + */ + removeEventListener(type: string, listener: (event: any) => void): void; + + /** + * Fire an event type. + * @param type The type of event that gets fired. + */ + dispatchEvent(event: { type: string; target: any; }): void; + } + + /** + * Triangle face. + * + * # Example + * var normal = new THREE.Vector3( 0, 1, 0 ); + * var color = new THREE.Color( 0xffaa00 ); + * var face = new THREE.Face3( 0, 1, 2, normal, color, 0 ); + * + * @source https://github.com/mrdoob/three.js/blob/master/src/core/Face3.js + */ + export class Face3 { + /** + * @param a Vertex A index. + * @param b Vertex B index. + * @param c Vertex C index. + * @param normal Face normal or array of vertex normals. + * @param color Face color or array of vertex colors. + * @param materialIndex Material index. + */ + constructor(a: number, b: number, c: number, normal?: Vector3, color?: Color, materialIndex?: number); + constructor(a: number, b: number, c: number, normal?: Vector3, vertexColors?: Color[], materialIndex?: number); + constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], color?: Color, materialIndex?: number); + constructor(a: number, b: number, c: number, vertexNormals?: Vector3[], vertexColors?: Color[], materialIndex?: number); + + /** + * Vertex A index. + */ + a: number; + + /** + * Vertex B index. + */ + b: number; + + /** + * Vertex C index. + */ + c: number; + + /** + * Face normal. + */ + normal: Vector3; + + /** + * Array of 4 vertex normals. + */ + vertexNormals: Vector3[]; + + /** + * Face color. + */ + color: Color; + + /** + * Array of 4 vertex normals. + */ + vertexColors: Color[]; + + /** + * Array of 4 vertex tangets. + */ + vertexTangents: number[]; + + /** + * Material index (points to {@link Geometry.materials}). + */ + materialIndex: number; + + clone(): Face3; + } + + export interface MorphTarget { + name: string; + vertices: Vector3[]; + } + + export interface MorphColor { + name: string; + colors: Color[]; + } + + export interface MorphNormals { + name: string; + normals: Vector3[]; + } + + export interface BoundingSphere { + radius: number; + } + + /** + * Base class for geometries + * + * # Example + * var geometry = new THREE.Geometry(); + * geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ) ); + * geometry.vertices.push( new THREE.Vector3( -10, -10, 0 ) ); + * geometry.vertices.push( new THREE.Vector3( 10, -10, 0 ) ); + * geometry.faces.push( new THREE.Face3( 0, 1, 2 ) ); + * geometry.computeBoundingSphere(); + * + * @see https://github.com/mrdoob/three.js/blob/master/src/core/Geometry.js + */ + export class Geometry { + constructor(); + + /** + * Unique number of this geometry instance + */ + id: number; + + uuid: string; + + /** + * Name for this geometry. Default is an empty string. + */ + name: string; + + type: string; + + /** + * The array of vertices hold every position of points of the model. + * To signal an update in this array, Geometry.verticesNeedUpdate needs to be set to true. + */ + vertices: Vector3[]; + + /** + * Array of vertex colors, matching number and order of vertices. + * Used in ParticleSystem, Line and Ribbon. + * Meshes use per-face-use-of-vertex colors embedded directly in faces. + * To signal an update in this array, Geometry.colorsNeedUpdate needs to be set to true. + */ + colors: Color[]; + + /** + * Array of triangles or/and quads. + * The array of faces describe how each vertex in the model is connected with each other. + * To signal an update in this array, Geometry.elementsNeedUpdate needs to be set to true. + */ + faces: Face3[]; + + /** + * Array of face UV layers. + * Each UV layer is an array of UV matching order and number of vertices in faces. + * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. + */ + faceVertexUvs: Vector2[][][]; + + /** + * Array of morph targets. Each morph target is a Javascript object: + * + * { name: "targetName", vertices: [ new THREE.Vector3(), ... ] } + * + * Morph vertices match number and order of primary vertices. + */ + morphTargets: MorphTarget[]; + + /** + * Array of morph normals. Morph normals have similar structure as morph targets, each normal set is a Javascript object: + * + * morphNormal = { name: "NormalName", normals: [ new THREE.Vector3(), ... ] } + */ + morphNormals: MorphNormals[]; + + /** + * Array of skinning weights, matching number and order of vertices. + */ + skinWeights: number[]; + + /** + * Array of skinning indices, matching number and order of vertices. + */ + skinIndices: number[]; + + /** + * + */ + lineDistances: number[]; + + /** + * Bounding box. + */ + boundingBox: Box3; + + /** + * Bounding sphere. + */ + boundingSphere: BoundingSphere; + + /** + * Set to true if the vertices array has been updated. + */ + verticesNeedUpdate: boolean; + + /** + * Set to true if the faces array has been updated. + */ + elementsNeedUpdate: boolean; + + /** + * Set to true if the uvs array has been updated. + */ + uvsNeedUpdate: boolean; + + /** + * Set to true if the normals array has been updated. + */ + normalsNeedUpdate: boolean; + + /** + * Set to true if the colors array has been updated. + */ + colorsNeedUpdate: boolean; + + /** + * Set to true if the linedistances array has been updated. + */ + lineDistancesNeedUpdate: boolean; + + /** + * + */ + groupsNeedUpdate: boolean; + + /** + * Bakes matrix transform directly into vertex coordinates. + */ + applyMatrix(matrix: Matrix4): void; + + rotateX(angle: number): Geometry; + rotateY(angle: number): Geometry; + rotateZ(angle: number): Geometry; + + translate(x: number, y: number, z: number): Geometry; + scale(x: number, y: number, z: number): Geometry; + lookAt( vector: Vector3 ): void; + + + fromBufferGeometry(geometry: BufferGeometry): Geometry; + + /** + * + */ + center(): Vector3; + + normalize(): Geometry; + + /** + * Computes face normals. + */ + computeFaceNormals(): void; + + /** + * Computes vertex normals by averaging face normals. + * Face normals must be existing / computed beforehand. + */ + computeVertexNormals(areaWeighted?: boolean): void; + + /** + * Computes morph normals. + */ + computeMorphNormals(): void; + + computeLineDistances(): void; + + /** + * Computes bounding box of the geometry, updating {@link Geometry.boundingBox} attribute. + */ + computeBoundingBox(): void; + + /** + * Computes bounding sphere of the geometry, updating Geometry.boundingSphere attribute. + * Neither bounding boxes or bounding spheres are computed by default. They need to be explicitly computed, otherwise they are null. + */ + computeBoundingSphere(): void; + + merge( geometry: Geometry, matrix: Matrix, materialIndexOffset?: number): void; + + mergeMesh( mesh: Mesh ): void; + + /** + * Checks for duplicate vertices using hashmap. + * Duplicated vertices are removed and faces' vertices are updated. + */ + mergeVertices(): number; + + sortFacesByMaterialIndex(): void; + + toJSON(): any; + + /** + * Creates a new clone of the Geometry. + */ + clone(): Geometry; + + copy(source: Geometry): Geometry; + + /** + * Removes The object from memory. + * Don't forget to call this method when you remove an geometry because it can cuase meomory leaks. + */ + dispose(): void; + + + //These properties do not exist in a normal Geometry class, but if you use the instance that was passed by JSONLoader, it will be added. + bones: Bone[]; + animation: AnimationClip; + animations: AnimationClip[]; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } + + /** + * @see src/core/InstancedBufferAttribute.js + */ + export class InstancedBufferAttribute extends BufferAttribute { + constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); + meshPerAttribute: number; + + clone(): InstancedBufferAttribute; + copy(source: InstancedBufferAttribute): InstancedBufferAttribute; + } + + /** + * @see src/core/InstancedBufferGeometry.js + */ + export class InstancedBufferGeometry extends BufferGeometry { + constructor(); + groups: {start:number, count:number, instances:number}[]; + addGroup(start: number, count: number, instances: number): void; + + clone(): InstancedBufferGeometry; + copy(source: InstancedBufferGeometry): InstancedBufferGeometry; + } + + /** + * @see src/core/InstancedInterleavedBuffer.js + */ + export class InstancedInterleavedBuffer extends InterleavedBuffer { + constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); + meshPerAttribute: number; + + clone(): InstancedInterleavedBuffer; + copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; + } + + /** + * @see src/core/InterleavedBuffer.js + */ + export class InterleavedBuffer { + constructor(array: ArrayLike, stride: number); + array: ArrayLike; + stride: number; + dynamic: boolean; + updateRange: {offset:number, count:number}; + version: number; + length: number; + count: number; + needsUpdate: boolean; + + setDynamic(dynamic: boolean): InterleavedBuffer; + clone(): InterleavedBuffer; + copy(source: InterleavedBuffer): InterleavedBuffer; + copyAt(index1: number, attribute: InterleavedBufferAttribute, index2: number): InterleavedBuffer; + set(value: ArrayLike, index: number): InterleavedBuffer; + clone(): InterleavedBuffer; + } + + /** + * @see src/core/InterleavedBufferAttribute.js + */ + export class InterleavedBufferAttribute { + constructor(interleavedBuffer: InterleavedBuffer, itemSize: number, offset: number); + + uuid: string; + data: InterleavedBuffer; + itemSize: number; + offset: number; + /** Deprecated, use count instead */ + length: number; + count: number; + + getX(index: number): number; + setX(index: number, x: number): InterleavedBufferAttribute; + getY(index: number): number; + setY(index: number, y: number): InterleavedBufferAttribute; + getZ(index: number): number; + setZ(index: number, z: number): InterleavedBufferAttribute; + getW(index: number): number; + setW(index: number, z: number): InterleavedBufferAttribute; + setXY(index: number, x: number, y: number): InterleavedBufferAttribute; + setXYZ(index: number, x: number, y: number, z: number): InterleavedBufferAttribute; + setXYZW(index: number, x: number, y: number, z: number, w: number): InterleavedBufferAttribute; + } + + /** + * Base class for scene graph objects + */ + export class Object3D { + constructor(); + + /** + * Unique number of this object instance. + */ + id: number; + + /** + * + */ + uuid: string; + + /** + * Optional name of the object (doesn't need to be unique). + */ + name: string; + + type: string; + + /** + * Object's parent in the scene graph. + */ + parent: Object3D; + + channels: Channels; + + /** + * Array with object's children. + */ + children: Object3D[]; + + /** + * Up direction. + */ + up: Vector3; + + /** + * Object's local position. + */ + position: Vector3; + + /** + * Object's local rotation (Euler angles), in radians. + */ + rotation: Euler; + + /** + * Global rotation. + */ + quaternion: Quaternion; + + /** + * Object's local scale. + */ + scale: Vector3; + + modelViewMatrix: Matrix4; + + normalMatrix: Matrix3; + + /** + * When this is set, then the rotationMatrix gets calculated every frame. + */ + rotationAutoUpdate: boolean; + + /** + * Local transform. + */ + matrix: Matrix4; + + /** + * The global transform of the object. If the Object3d has no parent, then it's identical to the local transform. + */ + matrixWorld: Matrix4; + + /** + * When this is set, it calculates the matrix of position, (rotation or quaternion) and scale every frame and also recalculates the matrixWorld property. + */ + matrixAutoUpdate: boolean; + + /** + * When this is set, it calculates the matrixWorld in that frame and resets this property to false. + */ + matrixWorldNeedsUpdate: boolean; + + /** + * Object gets rendered if true. + */ + visible: boolean; + + /** + * Gets rendered into shadow map. + */ + castShadow: boolean; + + /** + * Material gets baked in shadow receiving. + */ + receiveShadow: boolean; + + /** + * When this is set, it checks every frame if the object is in the frustum of the camera. Otherwise the object gets drawn every frame even if it isn't visible. + */ + frustumCulled: boolean; + + renderOrder: number; + + /** + * An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned. + */ + userData: any; + + /** + * + */ + static DefaultUp: Vector3; + static DefaultMatrixAutoUpdate: Vector3; + + /** + * This updates the position, rotation and scale with the matrix. + */ + applyMatrix(matrix: Matrix4): void; + + /** + * + */ + setRotationFromAxisAngle(axis: Vector3, angle: number): void; + + /** + * + */ + setRotationFromEuler(euler: Euler ): void; + + /** + * + */ + setRotationFromMatrix(m: Matrix4): void; + + /** + * + */ + setRotationFromQuaternion( q: Quaternion ): void; + + /** + * Rotate an object along an axis in object space. The axis is assumed to be normalized. + * @param axis A normalized vector in object space. + * @param angle The angle in radians. + */ + rotateOnAxis(axis: Vector3, angle: number): Object3D; + + /** + * + * @param angle + */ + rotateX(angle: number): Object3D; + + /** + * + * @param angle + */ + rotateY(angle: number): Object3D; + + /** + * + * @param angle + */ + rotateZ(angle: number): Object3D; + + /** + * @param axis A normalized vector in object space. + * @param distance The distance to translate. + */ + translateOnAxis(axis: Vector3, distance: number): Object3D; + + /** + * + * @param distance + * @param axis + */ + translate( distance: number, axis: Vector3 ): Object3D; + + /** + * Translates object along x axis by distance. + * @param distance Distance. + */ + translateX(distance: number): Object3D; + + /** + * Translates object along y axis by distance. + * @param distance Distance. + */ + translateY(distance: number): Object3D; + + /** + * Translates object along z axis by distance. + * @param distance Distance. + */ + translateZ(distance: number): Object3D; + + /** + * Updates the vector from local space to world space. + * @param vector A local vector. + */ + localToWorld(vector: Vector3): Vector3; + + /** + * Updates the vector from world space to local space. + * @param vector A world vector. + */ + worldToLocal(vector: Vector3): Vector3; + + /** + * Rotates object to face point in space. + * @param vector A world vector to look at. + */ + lookAt(vector: Vector3): void; + + /** + * Adds object as child of this object. + */ + add(object: Object3D): void; + + /** + * Removes object as child of this object. + */ + remove(object: Object3D): void; + + /* deprecated */ + getChildByName( name: string ): Object3D; + + /** + * Searches through the object's children and returns the first with a matching id, optionally recursive. + * @param id Unique number of the object instance + */ + getObjectById(id: number): Object3D; + + /** + * Searches through the object's children and returns the first with a matching name, optionally recursive. + * @param name String to match to the children's Object3d.name property. + */ + getObjectByName(name: string): Object3D; + + getObjectByProperty( name: string, value: string ): Object3D; + + getWorldPosition(optionalTarget?: Vector3): Vector3; + getWorldQuaternion(optionalTarget?: Quaternion): Quaternion; + getWorldRotation(optionalTarget?: Euler): Euler; + getWorldScale(optionalTarget?: Vector3): Vector3; + getWorldDirection(optionalTarget?: Vector3): Vector3; + + raycast(raycaster: Raycaster, intersects: any): void; + + traverse(callback: (object: Object3D) => any): void; + + traverseVisible(callback: (object: Object3D) => any): void; + + traverseAncestors(callback: (object: Object3D) => any): void; + + /** + * Updates local transform. + */ + updateMatrix(): void; + + /** + * Updates global transform of the object and its children. + */ + updateMatrixWorld(force: boolean): void; + + toJSON(meta?: any): any; + + clone(recursive?: boolean): Object3D; + + /** + * + * @param object + * @param recursive + */ + copy(source: Object3D, recursive?: boolean): Object3D; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + + } + + export interface Intersection { + distance: number; + point: Vector3; + face: Face3; + object: Object3D; + } + + export interface RaycasterParameters { + Mesh?: any; + Line?: any; + LOD?: any; + Points?: any; + Sprite?: any; + } + + export class Raycaster { + constructor(origin?: Vector3, direction?: Vector3, near?: number, far?: number); + + ray: Ray; + near: number; + far: number; + params: RaycasterParameters; + precision: number; + linePrecision: number; + set(origin: Vector3, direction: Vector3): void; + setFromCamera(coords: { x: number; y: number;}, camera: Camera ): void; + intersectObject(object: Object3D, recursive?: boolean): Intersection[]; + intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; + } + + // Lights ////////////////////////////////////////////////////////////////////////////////// + + /** + * Abstract base class for lights. + */ + export class Light extends Object3D { + constructor(hex?: number|string); + + color: Color; + receiveShadow: boolean; + + shadowCameraFov: number; + shadowCameraLeft: number; + shadowCameraRight: number; + shadowCameraTop: number; + shadowCameraBottom: number; + shadowCameraNear: number; + shadowCameraFar: number; + shadowBias: number; + shadowDarkness: number; + shadowMapWidth: number; + shadowMapHeight: number; + + clone(recursive?: boolean): Light; + copy( source: Light ): Light; + toJSON( meta: any ): any; + } + + export class LightShadow { + constructor(camera: Camera); + + camera: Camera; + bias: number; + darkness: number; + mapSize: Vector2; + map: RenderTarget; + matrix: Matrix4; + + copy(source: LightShadow): void; + clone(): LightShadow; + } + + /** + * This light's color gets applied to all the objects in the scene globally. + * + * # example + * var light = new THREE.AmbientLight( 0x404040 ); // soft white light + * scene.add( light ); + * + * @source https://github.com/mrdoob/three.js/blob/master/src/lights/AmbientLight.js + */ + export class AmbientLight extends Light { + /** + * This creates a Ambientlight with a color. + * @param hex Numeric value of the RGB component of the color. + */ + constructor(hex?: number|string); + + clone(recursive?: boolean): AmbientLight; + copy(source: AmbientLight): AmbientLight; + } + + /** + * Affects objects using MeshLambertMaterial or MeshPhongMaterial. + * + * @example + * // White directional light at half intensity shining from the top. + * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 ); + * directionalLight.position.set( 0, 1, 0 ); + * scene.add( directionalLight ); + * + * @see src/lights/DirectionalLight.js + */ + export class DirectionalLight extends Light { + + constructor(hex?: number|string, intensity?: number); + + /** + * Target used for shadow camera orientation. + */ + target: Object3D; + + /** + * Light's intensity. + * Default — 1.0. + */ + intensity: number; + + shadow: LightShadow; + + clone(recursive?: boolean): DirectionalLight; + copy(source: DirectionalLight): DirectionalLight; + } + + export class HemisphereLight extends Light { + constructor(skyColorHex?: number|string, groundColorHex?: number|string, intensity?: number); + + groundColor: Color; + intensity: number; + + clone(recursive?: boolean): HemisphereLight; + copy(source: HemisphereLight): HemisphereLight; + } + + /** + * Affects objects using {@link MeshLambertMaterial} or {@link MeshPhongMaterial}. + * + * @example + * var light = new THREE.PointLight( 0xff0000, 1, 100 ); + * light.position.set( 50, 50, 50 ); + * scene.add( light ); + */ + export class PointLight extends Light { + constructor(hex?: number|string, intensity?: number, distance?: number, decay?: number); + + /* + * Light's intensity. + * Default - 1.0. + */ + intensity: number; + + /** + * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. + * Default — 0.0. + */ + distance: number; + + decay: number; + + shadow: LightShadow; + + clone(recursive?: boolean): PointLight; + copy(source: PointLight): PointLight; + } + + /** + * A point light that can cast shadow in one direction. + */ + export class SpotLight extends Light { + constructor(hex?: number|string, intensity?: number, distance?: number, angle?: number, exponent?: number, decay?: number); + + /** + * Spotlight focus points at target.position. + * Default position — (0,0,0). + */ + target: Object3D; + + /** + * Light's intensity. + * Default — 1.0. + */ + intensity: number; + + /** + * If non-zero, light will attenuate linearly from maximum intensity at light position down to zero at distance. + * Default — 0.0. + */ + distance: number; + + /* + * Maximum extent of the spotlight, in radians, from its direction. + * Default — Math.PI/2. + */ + angle: number; + + /** + * Rapidity of the falloff of light from its target direction. + * Default — 10.0. + */ + exponent: number; + + decay: number; + + shadow: LightShadow; + + clone(recursive?: boolean): SpotLight; + copy(source: PointLight): SpotLight; + } + + // Loaders ////////////////////////////////////////////////////////////////////////////////// + + export interface Progress { + total: number; + loaded: number; + } + + /** + * Base class for implementing loaders. + * + * Events: + * load + * Dispatched when the image has completed loading + * content — loaded image + * + * error + * + * Dispatched when the image can't be loaded + * message — error message + */ + export class Loader { + constructor(); + + /** + * Will be called when load starts. + * The default is a function with empty body. + */ + onLoadStart: () => void; + + /** + * Will be called while load progresses. + * The default is a function with empty body. + */ + onLoadProgress: () => void; + + /** + * Will be called when load completes. + * The default is a function with empty body. + */ + onLoadComplete: () => void; + + /** + * default — null. + * If set, assigns the crossOrigin attribute of the image to the value of crossOrigin, prior to starting the load. + */ + crossOrigin: string; + + extractUrlBase(url: string): string; + initMaterials(materials: Material[], texturePath: string): Material[]; + createMaterial(m: Material, texturePath: string, crossOrigin?: string): boolean; + + static Handlers: LoaderHandler; + } + + export interface LoaderHandler{ + handlers:any[]; + add(regex:string, loader:Loader):void; + get(file: string):Loader; + } + + export class BinaryTextureLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; + } + + export class BufferGeometryLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): BufferGeometry; + } + + export interface Cache { + enabled: boolean; + files: any[]; + + add(key: string, file: any): void; + get(key: string): any; + remove(key: string): void; + clear(): void; + } + export var Cache: Cache; + + export class CompressedTextureLoader{ + constructor(manager?: LoadingManager); + + manager: LoadingManager; + load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; + } + + export class CubeTextureLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; + + } + + /** + * A loader for loading an image. + * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. + */ + export class ImageLoader { + constructor(manager?: LoadingManager); + + cache: Cache; + manager: LoadingManager; + crossOrigin: string; + + /** + * Begin loading from url + * @param url + */ + load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; + + setCrossOrigin(crossOrigin: string): void; + } + + /** + * A loader for loading objects in JSON format. + */ + export class JSONLoader extends Loader { + constructor(manager?: LoadingManager); + manager: LoadingManager; + withCredentials: boolean; + + load(url: string, onLoad?: (geometry: Geometry, materials: Material[]) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + + setCrossOrigin(crossOrigin: string): void; + setTexturePath( value: string ): void; + parse(json: any, texturePath?: string): { geometry: Geometry; materials?: Material[] }; + } + + /** + * Handles and keeps track of loaded and pending data. + */ + export class LoadingManager { + constructor(onLoad?: () => void, onProgress?: (url: string, loaded: number, total: number) => void, onError?: () => void); + + onStart: () => void; + + /** + * Will be called when load starts. + * The default is a function with empty body. + */ + onLoad: () => void; + + /** + * Will be called while load progresses. + * The default is a function with empty body. + */ + onProgress: (item: any, loaded: number, total: number) => void; + + /** + * Will be called when each element in the scene completes loading. + * The default is a function with empty body. + */ + onError: () => void; + + itemStart(url: string): void; + itemEnd(url: string): void; + itemError(url: string): void; + } + + export var DefaultLoadingManager: LoadingManager; + + export class MaterialLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + textures: { [key:string]:Texture }; + + load(url: string, onLoad: (material: Material) => void): void; + setCrossOrigin(crossOrigin: string): void; + setTextures(textures: { [key:string]:Texture }): void; + getTexture( name: string ):Texture; + parse(json: any): Material; + } + + export class ObjectLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + texturePass: string; + + load(url: string, onLoad?: (object: Object3D) => void): void; + setTexturePath( value: string ): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any, onLoad?: (object: Object3D) => void): T; + parseGeometries(json: any): any[]; // Array of BufferGeometry or Geometry or Geometry2. + parseMaterials(json: any, textures: Texture[]): Material[]; // Array of Classes that inherits from Matrial. + parseImages( json: any, onLoad: () => void ): any[]; + parseTextures( json: any, images: any ): Texture[]; + parseObject(data: any, geometries: any[], materials: Material[]): T; + + } + + /** + * Class for loading a texture. + * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. + */ + export class TextureLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + crossOrigin: string; + + /** + * Begin loading from url + * + * @param url + */ + load(url: string, onLoad?: (texture: Texture) => void): Texture; + setCrossOrigin(crossOrigin: string): void; + } + + export class XHRLoader { + constructor(manager?: LoadingManager); + + cache: Cache; + manager: LoadingManager; + responseType: string; + crossOrigin: string; + + load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): any; + setResponseType(responseType: string): void; + setCrossOrigin(crossOrigin: string): void; + setWithCredentials( withCredentials: string ): void; + } + + // Materials ////////////////////////////////////////////////////////////////////////////////// + export interface MaterialParameters { + name?: string; + side?: Side; + opacity?: number; + transparent?: boolean; + blending?: Blending; + blendSrc?: BlendingDstFactor; + blendDst?: BlendingSrcFactor; + blendEquation?: BlendingEquation; + depthTest?: boolean; + depthWrite?: boolean; + polygonOffset?: boolean; + polygonOffsetFactor?: number; + polygonOffsetUnits?: number; + alphaTest?: number; + overdraw?: number; + visible?: boolean; + needsUpdate?: boolean; + } + + /** + * Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use a different renderer. + */ + export class Material { + constructor(); + + /** + * Unique number of this material instance. + */ + id: number; + + uuid: string; + + /** + * Material name. Default is an empty string. + */ + name: string; + + type: string; + + /** + * Defines which of the face sides will be rendered - front, back or both. + * Default is THREE.FrontSide. Other options are THREE.BackSide and THREE.DoubleSide. + */ + side: Side; + + /** + * Opacity. Default is 1. + */ + opacity: number; + + /** + * Defines whether this material is transparent. This has an effect on rendering, as transparent objects need an special treatment, and are rendered after the opaque (i.e. non transparent) objects. For a working example of this behaviour, check the {@link WebGLRenderer} code. + * Default is false. + */ + transparent: boolean; + + /** + * Which blending to use when displaying objects with this material. Default is {@link NormalBlending}. + */ + blending: Blending; + + /** + * Blending source. It's one of the blending mode constants defined in Three.js. Default is {@link SrcAlphaFactor}. + */ + blendSrc: BlendingDstFactor; + + /** + * Blending destination. It's one of the blending mode constants defined in Three.js. Default is {@link OneMinusSrcAlphaFactor}. + */ + blendDst: BlendingSrcFactor; + + /** + * Blending equation to use when applying blending. It's one of the constants defined in Three.js. Default is AddEquation. + */ + blendEquation: BlendingEquation; + + blendSrcAlpha: number; + blendDstAlpha: number; + blendEquationAlpha: number; + + depthFunc: DepthModes; + + /** + * Whether to have depth test enabled when rendering this material. Default is true. + */ + depthTest: boolean; + + /** + * Whether rendering this material has any effect on the depth buffer. Default is true. + * When drawing 2D overlays it can be useful to disable the depth writing in order to layer several things together without creating z-index artifacts. + */ + depthWrite: boolean; + + colorWrite: boolean; + + precision: any; + + /** + * Whether to use polygon offset. Default is false. This corresponds to the POLYGON_OFFSET_FILL WebGL feature. + */ + polygonOffset: boolean; + + /** + * Sets the polygon offset factor. Default is 0. + */ + polygonOffsetFactor: number; + + /** + * Sets the polygon offset units. Default is 0. + */ + polygonOffsetUnits: number; + + /** + * Sets the alpha value to be used when running an alpha test. Default is 0. + */ + alphaTest: number; + + /** + * Enables/disables overdraw. If greater than zero, polygons are drawn slightly bigger in order to fix antialiasing gaps when using the CanvasRenderer. Default is 0. + */ + overdraw: number; + + /** + * Defines whether this material is visible. Default is true. + */ + visible: boolean; + + /** + * Specifies that the material needs to be updated, WebGL wise. Set it to true if you made changes that need to be reflected in WebGL. + * This property is automatically set to true when instancing a new material. + */ + needsUpdate: boolean; + + setValues(values: Object): void; + toJSON(meta?: any): any; + clone(): Material; + clone(source?:Material): Material; + update(): void; + dispose(): void; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } + + export interface LineBasicMaterialParameters extends MaterialParameters { + color?: number|string; + linewidth?: number; + linecap?: string; + linejoin?: string; + vertexColors?: Colors; + fog?: boolean; + } + + export class LineBasicMaterial extends Material { + constructor(parameters?: LineBasicMaterialParameters); + + color: Color; + linewidth: number; + linecap: string; + linejoin: string; + vertexColors: Colors; + fog: boolean; + + clone(): LineBasicMaterial; + copy(source: LineBasicMaterial): LineBasicMaterial; + } + + export interface LineDashedMaterialParameters extends MaterialParameters { + color?: number|string; + linewidth?: number; + scale?: number; + dashSize?: number; + gapSize?: number; + vertexColors?: Colors; + fog?: boolean; + } + + export class LineDashedMaterial extends Material { + constructor(parameters?: LineDashedMaterialParameters); + + color: Color; + linewidth: number; + scale: number; + dashSize: number; + gapSize: number; + vertexColors: Colors; + fog: boolean; + + clone(): LineDashedMaterial; + copy(source: LineDashedMaterial): LineDashedMaterial; + } + + /** + * parameters is an object with one or more properties defining the material's appearance. + */ + export interface MeshBasicMaterialParameters extends MaterialParameters{ + color?: number|string; + opacity?: number; + map?: Texture; + aoMap?: Texture; + aoMapIntensity?: number; + specularMap?: Texture; + alphaMap?: Texture; + envMap?: Texture; + combine?: Combine; + reflectivity?: number; + refractionRatio?: number; + shading?: Shading; + blending?: Blending; + depthTest?: boolean; + depthWrite?: boolean; + wireframe?: boolean; + wireframeLinewidth?: number; + vertexColors?: Colors; + skinning?: boolean; + morphTargets?: boolean; + fog?: boolean; + } + + export class MeshBasicMaterial extends Material { + constructor(parameters?: MeshBasicMaterialParameters); + + color: Color; + map: Texture; + aoMap: Texture; + aoMapIntensity: number; + specularMap: Texture; + alphaMap: Texture; + envMap: Texture; + combine: Combine; + reflectivity: number; + refractionRatio: number; + fog: boolean; + shading: Shading; + wireframe: boolean; + wireframeLinewidth: number; + wireframeLinecap: string; + wireframeLinejoin: string; + vertexColors: Colors; + skinning: boolean; + morphTargets: boolean; + + clone(): MeshBasicMaterial; + copy(source: MeshBasicMaterial): MeshBasicMaterial; + } + + export interface MeshDepthMaterialParameters extends MaterialParameters{ + wireframe?: boolean; + wireframeLinewidth?: number; + } + + export class MeshDepthMaterial extends Material { + constructor(parameters?: MeshDepthMaterialParameters); + + wireframe: boolean; + wireframeLinewidth: number; + + clone(): MeshDepthMaterial; + copy(source: MeshDepthMaterial): MeshDepthMaterial; + } + + export interface MeshLambertMaterialParameters extends MaterialParameters{ + color?: number|string; + emissive?: number; + opacity?: number; + map?: Texture; + specularMap?: Texture; + alphaMap?: Texture; + envMap?: Texture; + combine?: Combine; + reflectivity?: number; + refractionRatio?: number; + fog?: boolean; + wireframe?: boolean; + wireframeLinewidth?: number; + vertexColors?: Colors; + skinning?: boolean; + morphTargets?: boolean; + morphNormals?: boolean; + } + + export class MeshLambertMaterial extends Material { + constructor(parameters?: MeshLambertMaterialParameters); + + color: Color; + emissive: Color; + map: Texture; + specularMap: Texture; + alphaMap: Texture; + envMap: Texture; + combine: Combine; + reflectivity: number; + refractionRatio: number; + fog: boolean; + wireframe: boolean; + wireframeLinewidth: number; + wireframeLinecap: string; + wireframeLinejoin: string; + vertexColors: Colors; + skinning: boolean; + morphTargets: boolean; + morphNormals: boolean; + + clone(): MeshLambertMaterial; + copy(source: MeshLambertMaterial): MeshLambertMaterial; + } + + export interface MeshNormalMaterialParameters extends MaterialParameters{ + opacity?: number; + shading?: Shading; + blending?: Blending; + depthTest?: boolean; + depthWrite?: boolean; + + /** Render geometry as wireframe. Default is false (i.e. render as smooth shaded). */ + wireframe?: boolean; + /** Controls wireframe thickness. Default is 1. */ + wireframeLinewidth?: number; + + } + + export class MeshNormalMaterial extends Material { + constructor(parameters?: MeshNormalMaterialParameters); + + wireframe: boolean; + wireframeLinewidth: number; + morphTargets: boolean; + + clone(): MeshNormalMaterial; + copy(source: MeshNormalMaterial): MeshNormalMaterial; + } + + export interface MeshPhongMaterialParameters extends MaterialParameters { + /** geometry color in hexadecimal. Default is 0xffffff. */ + color?: number | string; + emissive?: number; + specular?: number; + shininess?: number; + opacity?: number; + map?: Texture; + lightMap?: Texture; + lightMapIntensity?: number; + aoMap?: Texture; + aoMapIntensity?: number; + emissiveMap?: Texture; + bumpMap?: Texture; + bumpScale?: number; + normalMap?: Texture; + normalScale?: Vector2; + displacementMap?: Texture; + displacementScale?: number; + displacementBias?: number; + specularMap?: Texture; + alphaMap?: Texture; + envMap?: Texture; + combine?: Combine; + reflectivity?: number; + refractionRatio?: number; + shading?: Shading; + blending?: Blending; + depthTest?: boolean; + depthWrite?: boolean; + wireframe?: boolean; + wireframeLinewidth?: number; + vertexColors?: Colors; + skinning?: boolean; + morphTargets?: boolean; + morphNormals?: boolean; + fog?: boolean; + } + + export class MeshPhongMaterial extends Material { + constructor(parameters?: MeshPhongMaterialParameters); + + color: Color; // diffuse + emissive: Color; + specular: Color; + shininess: number; + metal: boolean; + map: Texture; + lightMap: Texture; + lightMapIntensity: number; + aoMap: Texture; + aoMapIntensity: number; + emissiveMap: Texture; + bumpMap: Texture; + bumpScale: number; + normalMap: Texture; + normalScale: Vector2; + displacementMap: Texture; + displacementScale: number; + displacementBias: number; + specularMap: Texture; + alphaMap: Texture; + envMap: Texture; + combine: Combine; + reflectivity: number; + refractionRatio: number; + fog: boolean; + shading: Shading; + wireframe: boolean; + wireframeLinewidth: number; + wireframeLinecap: string; + wireframeLinejoin: string; + vertexColors: Colors; + skinning: boolean; + morphTargets: boolean; + morphNormals: boolean; + + clone(): MeshPhongMaterial; + copy(source: MeshPhongMaterial): MeshPhongMaterial; + } + + // MultiMaterial does not inherit the Material class in the original code. However, it should treat as Material class. + // See tests/canvas/canvas_materials.ts. + export class MultiMaterial extends Material { + constructor(materials?: Material[]); + materials: Material[]; + + toJSON(): any; + clone(): MultiMaterial; + } + + // deprecated + export class MeshFaceMaterial extends MultiMaterial { + + } + + export interface PointsMaterialParameters extends MaterialParameters{ + color?: number|string; + opacity?: number; + map?: Texture; + size?: number; + sizeAttenuation?: boolean; + blending?: Blending, + depthTest?: boolean; + depthWrite?: boolean; + vertexColors?: Colors; + fog?: boolean; + } + + export class PointsMaterial extends Material { + constructor(parameters?: PointsMaterialParameters); + + color: Color; + map: Texture; + size: number; + sizeAttenuation: boolean; + vertexColors: boolean; + fog: boolean; + + clone(): PointsMaterial; + copy(source: PointsMaterial): PointsMaterial; + } + + export class RawShaderMaterial extends ShaderMaterial { + constructor(parameters?: ShaderMaterialParameters); + } + + export interface ShaderMaterialParameters extends MaterialParameters { + defines?: any; + uniforms?: any; + fragmentShader?: string; + vertexShader?: string; + shading?: Shading; + blending?: Blending; + depthTest?: boolean; + depthWrite?: boolean; + wireframe?: boolean; + wireframeLinewidth?: number; + lights?: boolean; + vertexColors?: Colors; + skinning?: boolean; + morphTargets?: boolean; + morphNormals?: boolean; + fog?: boolean; + } + + export class ShaderMaterial extends Material { + constructor(parameters?: ShaderMaterialParameters); + + defines: any; + uniforms: any; + vertexShader: string; + fragmentShader: string; + shading: Shading; + linewidth: number; + wireframe: boolean; + wireframeLinewidth: number; + fog: boolean; + lights: boolean; + vertexColors: Colors; + skinning: boolean; + morphTargets: boolean; + morphNormals: boolean; + derivatives: boolean; + defaultAttributeValues: any; + index0AttributeName: string; + + clone(): ShaderMaterial; + copy(source: ShaderMaterial): ShaderMaterial; + toJSON(meta: any): any; + } + + export interface SpriteMaterialParameters extends MaterialParameters { + color?: number|string; + opacity?: number; + map?: Texture; + blending?: Blending; + depthTest?: boolean; + depthWrite?: boolean; + uvOffset?: Vector2; + uvScale?: Vector2; + fog?: boolean; + } + + export class SpriteMaterial extends Material { + constructor(parameters?: SpriteMaterialParameters); + + color: Color; + map: Texture; + rotation: number; + fog: boolean; + + clone(): SpriteMaterial; + copy(source: SpriteMaterial): SpriteMaterial; + } + + // Math ////////////////////////////////////////////////////////////////////////////////// + + export class Box2 { + constructor(min?: Vector2, max?: Vector2); + + max: Vector2; + min: Vector2; + + set(min: Vector2, max: Vector2): Box2; + setFromPoints(points: Vector2[]): Box2; + setFromCenterAndSize(center: Vector2, size: Vector2): Box2; + clone(): Box2; + copy(box: Box2): Box2; + makeEmpty(): Box2; + empty(): boolean; + center(optionalTarget?: Vector2): Vector2; + size(optionalTarget?: Vector2): Vector2; + expandByPoint(point: Vector2): Box2; + expandByVector(vector: Vector2): Box2; + expandByScalar(scalar: number): Box2; + containsPoint(point: Vector2): boolean; + containsBox(box: Box2): boolean; + getParameter(point: Vector2): Vector2; + isIntersectionBox(box: Box2): boolean; + clampPoint(point: Vector2, optionalTarget?: Vector2): Vector2; + distanceToPoint(point: Vector2): number; + intersect(box: Box2): Box2; + union(box: Box2): Box2; + translate(offset: Vector2): Box2; + equals(box: Box2): boolean; + } + + export class Box3 { + constructor(min?: Vector3, max?: Vector3); + + max: Vector3; + min: Vector3; + + set(min: Vector3, max: Vector3): Box3; + setFromPoints(points: Vector3[]): Box3; + setFromCenterAndSize(center: Vector3, size: Vector3): Box3; + setFromObject(object: Object3D): Box3; + clone(): Box3; + copy(box: Box3): Box3; + makeEmpty(): Box3; + empty(): boolean; + center(optionalTarget?: Vector3): Vector3; + size(optionalTarget?: Vector3): Vector3; + expandByPoint(point: Vector3): Box3; + expandByVector(vector: Vector3): Box3; + expandByScalar(scalar: number): Box3; + containsPoint(point: Vector3): boolean; + containsBox(box: Box3): boolean; + getParameter(point: Vector3): Vector3; + isIntersectionBox(box: Box3): boolean; + clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + distanceToPoint(point: Vector3): number; + getBoundingSphere(optionalTarget?: Sphere): Sphere; + intersect(box: Box3): Box3; + union(box: Box3): Box3; + applyMatrix4(matrix: Matrix4): Box3; + translate(offset: Vector3): Box3; + equals(box: Box3): boolean; + } + + export interface HSL { + h: number; + s: number; + l: number; + } + + /** + * Represents a color. See also {@link ColorUtils}. + * + * @example + * var color = new THREE.Color( 0xff0000 ); + * + * @see src/math/Color.js + */ + export class Color { + constructor(color?: Color); + constructor(color?: string); + constructor(color?: number); + constructor(r: number, g: number, b: number); + + /** + * Red channel value between 0 and 1. Default is 1. + */ + r: number; + + /** + * Green channel value between 0 and 1. Default is 1. + */ + g: number; + + /** + * Blue channel value between 0 and 1. Default is 1. + */ + b: number; + + set(color: Color): Color; + set(color: number): Color; + set(color: string): Color; + setHex(hex: number): Color; + + /** + * Sets this color from RGB values. + * @param r Red channel value between 0 and 1. + * @param g Green channel value between 0 and 1. + * @param b Blue channel value between 0 and 1. + */ + setRGB(r: number, g: number, b: number): Color; + + /** + * Sets this color from HSL values. + * Based on MochiKit implementation by Bob Ippolito. + * + * @param h Hue channel value between 0 and 1. + * @param s Saturation value channel between 0 and 1. + * @param l Value channel value between 0 and 1. + */ + setHSL(h: number, s: number, l: number): Color; + + /** + * Sets this color from a CSS context style string. + * @param contextStyle Color in CSS context style format. + */ + setStyle(style: string): Color; + + /** + * Clones this color. + */ + clone(): Color; + + /** + * Copies given color. + * @param color Color to copy. + */ + copy(color: Color): Color; + + /** + * Copies given color making conversion from gamma to linear space. + * @param color Color to copy. + */ + copyGammaToLinear(color: Color, gammaFactor?: number): Color; + + /** + * Copies given color making conversion from linear to gamma space. + * @param color Color to copy. + */ + copyLinearToGamma(color: Color, gammaFactor?: number): Color; + + /** + * Converts this color from gamma to linear space. + */ + convertGammaToLinear(): Color; + + /** + * Converts this color from linear to gamma space. + */ + convertLinearToGamma(): Color; + + /** + * Returns the hexadecimal value of this color. + */ + getHex(): number; + + /** + * Returns the string formated hexadecimal value of this color. + */ + getHexString(): string; + + getHSL(): HSL; + + /** + * Returns the value of this color in CSS context style. + * Example: rgb(r, g, b) + */ + getStyle(): string; + + offsetHSL(h: number, s: number, l: number): Color; + + add(color: Color): Color; + addColors(color1: Color, color2: Color): Color; + addScalar(s: number): Color; + multiply(color: Color): Color; + multiplyScalar(s: number): Color; + lerp(color: Color, alpha: number): Color; + equals(color: Color): boolean; + fromArray(rgb: number[], offset?: number): Color; + toArray(array?: number[], offset?: number): number[]; + } + + export class ColorKeywords { + static aliceblue: number; + static antiquewhite: number; + static aqua: number; + static aquamarine: number; + static azure: number; + static beige: number; + static bisque: number; + static black: number; + static blanchedalmond: number; + static blue: number; + static blueviolet: number; + static brown: number; + static burlywood: number; + static cadetblue: number; + static chartreuse: number; + static chocolate: number; + static coral: number; + static cornflowerblue: number; + static cornsilk: number; + static crimson: number; + static cyan: number; + static darkblue: number; + static darkcyan: number; + static darkgoldenrod: number; + static darkgray: number; + static darkgreen: number; + static darkgrey: number; + static darkkhaki: number; + static darkmagenta: number; + static darkolivegreen: number; + static darkorange: number; + static darkorchid: number; + static darkred: number; + static darksalmon: number; + static darkseagreen: number; + static darkslateblue: number; + static darkslategray: number; + static darkslategrey: number; + static darkturquoise: number; + static darkviolet: number; + static deeppink: number; + static deepskyblue: number; + static dimgray: number; + static dimgrey: number; + static dodgerblue: number; + static firebrick: number; + static floralwhite: number; + static forestgreen: number; + static fuchsia: number; + static gainsboro: number; + static ghostwhite: number; + static gold: number; + static goldenrod: number; + static gray: number; + static green: number; + static greenyellow: number; + static grey: number; + static honeydew: number; + static hotpink: number; + static indianred: number; + static indigo: number; + static ivory: number; + static khaki: number; + static lavender: number; + static lavenderblush: number; + static lawngreen: number; + static lemonchiffon: number; + static lightblue: number; + static lightcoral: number; + static lightcyan: number; + static lightgoldenrodyellow: number; + static lightgray: number; + static lightgreen: number; + static lightgrey: number; + static lightpink: number; + static lightsalmon: number; + static lightseagreen: number; + static lightskyblue: number; + static lightslategray: number; + static lightslategrey: number; + static lightsteelblue: number; + static lightyellow: number; + static lime: number; + static limegreen: number; + static linen: number; + static magenta: number; + static maroon: number; + static mediumaquamarine: number; + static mediumblue: number; + static mediumorchid: number; + static mediumpurple: number; + static mediumseagreen: number; + static mediumslateblue: number; + static mediumspringgreen: number; + static mediumturquoise: number; + static mediumvioletred: number; + static midnightblue: number; + static mintcream: number; + static mistyrose: number; + static moccasin: number; + static navajowhite: number; + static navy: number; + static oldlace: number; + static olive: number; + static olivedrab: number; + static orange: number; + static orangered: number; + static orchid: number; + static palegoldenrod: number; + static palegreen: number; + static paleturquoise: number; + static palevioletred: number; + static papayawhip: number; + static peachpuff: number; + static peru: number; + static pink: number; + static plum: number; + static powderblue: number; + static purple: number; + static red: number; + static rosybrown: number; + static royalblue: number; + static saddlebrown: number; + static salmon: number; + static sandybrown: number; + static seagreen: number; + static seashell: number; + static sienna: number; + static silver: number; + static skyblue: number; + static slateblue: number; + static slategray: number; + static slategrey: number; + static snow: number; + static springgreen: number; + static steelblue: number; + static tan: number; + static teal: number; + static thistle: number; + static tomato: number; + static turquoise: number; + static violet: number; + static wheat: number; + static white: number; + static whitesmoke: number; + static yellow: number; + static yellowgreen: number; + } + + export class Euler { + static DefaultOrder: string; + + constructor(x?: number, y?: number, z?: number, order?: string); + + x: number; + y: number; + z: number; + order: string; + + set(x: number, y: number, z: number, order?: string): Euler; + clone(): Euler; + copy(euler: Euler): Euler; + setFromRotationMatrix(m: Matrix4, order?: string, update?: boolean): Euler; + setFromQuaternion(q:Quaternion, order?: string, update?: boolean): Euler; + setFromVector3( v: Vector3, order?: string ): Euler; + reorder(newOrder: string): Euler; + equals(euler: Euler): boolean; + fromArray(xyzo: any[]): Euler; + toArray(array?: number[], offset?: number): number[]; + toVector3(optionalResult?: Vector3): Vector3; + onChange: () => void; + } + + /** + * Frustums are used to determine what is inside the camera's field of view. They help speed up the rendering process. + */ + export class Frustum { + constructor(p0?: Plane, p1?: Plane, p2?: Plane, p3?: Plane, p4?: Plane, p5?: Plane); + + /** + * Array of 6 vectors. + */ + planes: Plane[]; + + set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; + clone(): Frustum; + copy(frustum: Frustum): Frustum; + setFromMatrix(m: Matrix4): Frustum; + intersectsObject(object: Object3D): boolean; + intersectsSphere(sphere: Sphere): boolean; + intersectsBox(box: Box3): boolean; + containsPoint(point: Vector3): boolean; + } + + export class Line3 { + constructor(start?: Vector3, end?: Vector3); + start: Vector3; + end: Vector3; + + set(start?: Vector3, end?: Vector3): Line3; + clone(): Line3; + copy(line: Line3): Line3; + center(optionalTarget?: Vector3): Vector3; + delta(optionalTarget?: Vector3): Vector3; + distanceSq(): number; + distance(): number; + at(t: number, optionalTarget?: Vector3): Vector3; + closestPointToPointParameter(point: Vector3, clampToLine?: boolean): number; + closestPointToPoint(point: Vector3, clampToLine?: boolean, optionalTarget?: Vector3): Vector3; + applyMatrix4(matrix: Matrix4): Line3; + equals(line: Line3): boolean; + } + + interface Math { + generateUUID(): string; + + /** + * Clamps the x to be between a and b. + * + * @param value Value to be clamped. + * @param min Minimum value + * @param max Maximum value. + */ + clamp(value: number, min: number, max: number): number; + euclideanModulo( n: number, m: number ): number; + + /** + * Linear mapping of x from range [a1, a2] to range [b1, b2]. + * + * @param x Value to be mapped. + * @param a1 Minimum value for range A. + * @param a2 Maximum value for range A. + * @param b1 Minimum value for range B. + * @param b2 Maximum value for range B. + */ + mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number; + + smoothstep(x: number, min: number, max: number): number; + + smootherstep(x: number, min: number, max: number): number; + + /** + * Random float from 0 to 1 with 16 bits of randomness. + * Standard Math.random() creates repetitive patterns when applied over larger space. + */ + random16(): number; + + /** + * Random integer from low to high interval. + */ + randInt(low: number, high: number): number; + + /** + * Random float from low to high interval. + */ + randFloat(low: number, high: number): number; + + /** + * Random float from - range / 2 to range / 2 interval. + */ + randFloatSpread(range: number): number; + + degToRad(degrees: number): number; + + radToDeg(radians: number): number; + + isPowerOfTwo(value: number): boolean; + + nearestPowerOfTwo(value: number): number; + + nextPowerOfTwo(value: number): number; + } + + /** + * + * @see src/math/Math.js + */ + export var Math: Math; + + /** + * ( interface Matrix<T> ) + */ + export interface Matrix { + /** + * Float32Array with matrix values. + */ + elements: Float32Array; + + /** + * identity():T; + */ + identity(): Matrix; + + /** + * copy(m:T):T; + */ + copy(m: Matrix): Matrix; + + /** + * multiplyScalar(s:number):T; + */ + multiplyScalar(s: number): Matrix; + + determinant(): number; + + /** + * getInverse(matrix:T, throwOnInvertible?:boolean):T; + */ + getInverse(matrix: Matrix, throwOnInvertible?: boolean): Matrix; + + /** + * transpose():T; + */ + transpose(): Matrix; + + /** + * clone():T; + */ + clone(): Matrix; + } + + /** + * ( class Matrix3 implements Matrix<Matrix3> ) + */ + export class Matrix3 implements Matrix { + /** + * Creates an identity matrix. + */ + constructor(); + + /** + * Initialises the matrix with the supplied n11..n33 values. + */ + constructor(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number); + + /** + * Float32Array with matrix values. + */ + elements: Float32Array; + + set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; + identity(): Matrix3; + clone(): Matrix3; + copy(m: Matrix3): Matrix3; + applyToVector3Array(array: number[], offset?: number, length?: number): number[]; + applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; + multiplyScalar(s: number): Matrix3; + determinant(): number; + getInverse(matrix: Matrix3, throwOnInvertible?: boolean): Matrix3; + getInverse(matrix: Matrix4, throwOnInvertible?: boolean): Matrix3; + + /** + * Transposes this matrix in place. + */ + transpose(): Matrix3; + flattenToArrayOffset(array: number[], offset: number): number[]; + getNormalMatrix(m: Matrix4): Matrix3; + + /** + * Transposes this matrix into the supplied array r, and returns itself. + */ + transposeIntoArray(r: number[]): number[]; + fromArray(array: number[]): Matrix3; + toArray(): number[]; + + } + + /** + * A 4x4 Matrix. + * + * @example + * // Simple rig for rotating around 3 axes + * var m = new THREE.Matrix4(); + * var m1 = new THREE.Matrix4(); + * var m2 = new THREE.Matrix4(); + * var m3 = new THREE.Matrix4(); + * var alpha = 0; + * var beta = Math.PI; + * var gamma = Math.PI/2; + * m1.makeRotationX( alpha ); + * m2.makeRotationY( beta ); + * m3.makeRotationZ( gamma ); + * m.multiplyMatrices( m1, m2 ); + * m.multiply( m3 ); + */ + export class Matrix4 implements Matrix { + /** + * Initialises the matrix with the supplied n11..n44 values. + */ + constructor(n11?: number, n12?: number, n13?: number, n14?: number, n21?: number, n22?: number, n23?: number, n24?: number, n31?: number, n32?: number, n33?: number, n34?: number, n41?: number, n42?: number, n43?: number, n44?: number); + + /** + * Float32Array with matrix values. + */ + elements: Float32Array; + + /** + * Sets all fields of this matrix. + */ + set(n11: number, n12: number, n13: number, n14: number, n21: number, n22: number, n23: number, n24: number, n31: number, n32: number, n33: number, n34: number, n41: number, n42: number, n43: number, n44: number): Matrix4; + + /** + * Resets this matrix to identity. + */ + identity(): Matrix4; + clone(): Matrix4; + copy(m: Matrix4): Matrix4; + copyPosition(m: Matrix4): Matrix4; + extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; + makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; + + /** + * Copies the rotation component of the supplied matrix m into this matrix rotation component. + */ + extractRotation(m: Matrix4): Matrix4; + makeRotationFromEuler(euler: Euler): Matrix4; + makeRotationFromQuaternion(q: Quaternion): Matrix4; + /** + * Constructs a rotation matrix, looking from eye towards center with defined up vector. + */ + lookAt(eye: Vector3, target: Vector3, up: Vector3): Matrix4; + + /** + * Multiplies this matrix by m. + */ + multiply(m: Matrix4): Matrix4; + + /** + * Sets this matrix to a x b. + */ + multiplyMatrices(a: Matrix4, b: Matrix4): Matrix4; + + /** + * Sets this matrix to a x b and stores the result into the flat array r. + * r can be either a regular Array or a TypedArray. + */ + multiplyToArray(a: Matrix4, b: Matrix4, r: number[]): Matrix4; + + /** + * Multiplies this matrix by s. + */ + multiplyScalar(s: number): Matrix4; + applyToVector3Array(array: number[], offset?: number, length?: number): number[]; + applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; + /** + * Computes determinant of this matrix. + * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm + */ + determinant(): number; + + /** + * Transposes this matrix. + */ + transpose(): Matrix4; + + /** + * Flattens this matrix into supplied flat array starting from offset position in the array. + */ + flattenToArrayOffset(array: number[], offset: number): number[]; + + /** + * Sets the position component for this matrix from vector v. + */ + setPosition(v: Vector3): Vector3; + + /** + * Sets this matrix to the inverse of matrix m. + * Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm. + */ + getInverse(m: Matrix4, throwOnInvertible?: boolean): Matrix4; + + /** + * Multiplies the columns of this matrix by vector v. + */ + scale(v: Vector3): Matrix4; + + getMaxScaleOnAxis(): number; + /** + * Sets this matrix as translation transform. + */ + makeTranslation(x: number, y: number, z: number): Matrix4; + + /** + * Sets this matrix as rotation transform around x axis by theta radians. + * + * @param theta Rotation angle in radians. + */ + makeRotationX(theta: number): Matrix4; + + /** + * Sets this matrix as rotation transform around y axis by theta radians. + * + * @param theta Rotation angle in radians. + */ + makeRotationY(theta: number): Matrix4; + + /** + * Sets this matrix as rotation transform around z axis by theta radians. + * + * @param theta Rotation angle in radians. + */ + makeRotationZ(theta: number): Matrix4; + + /** + * Sets this matrix as rotation transform around axis by angle radians. + * Based on http://www.gamedev.net/reference/articles/article1199.asp. + * + * @param axis Rotation axis. + * @param theta Rotation angle in radians. + */ + makeRotationAxis(axis: Vector3, angle: number): Matrix4; + + /** + * Sets this matrix as scale transform. + */ + makeScale(x: number, y: number, z: number): Matrix4; + + /** + * Sets this matrix to the transformation composed of translation, rotation and scale. + */ + compose(translation: Vector3, rotation: Quaternion, scale: Vector3): Matrix4; + + /** + * Decomposes this matrix into the translation, rotation and scale components. + * If parameters are not passed, new instances will be created. + */ + decompose(translation?: Vector3, rotation?: Quaternion, scale?: Vector3): Object[]; // [Vector3, Quaternion, Vector3] + + /** + * Creates a frustum matrix. + */ + makeFrustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; + + /** + * Creates a perspective projection matrix. + */ + makePerspective(fov: number, aspect: number, near: number, far: number): Matrix4; + + /** + * Creates an orthographic projection matrix. + */ + makeOrthographic(left: number, right: number, top: number, bottom: number, near: number, far: number): Matrix4; + equals( matrix: Matrix4 ): boolean; + fromArray(array: number[]): Matrix4; + toArray(): number[]; + } + + export class Plane { + constructor(normal?: Vector3, constant?: number); + + normal: Vector3; + constant: number; + + set(normal: Vector3, constant: number): Plane; + setComponents(x: number, y: number, z: number, w: number): Plane; + setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; + setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; + clone(): Plane; + copy(plane: Plane): Plane; + normalize(): Plane; + negate(): Plane; + distanceToPoint(point: Vector3): number; + distanceToSphere(sphere: Sphere): number; + projectPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + orthoPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + isIntersectionLine(line: Line3): boolean; + intersectLine(line: Line3, optionalTarget?: Vector3): Vector3; + coplanarPoint(optionalTarget?: boolean): Vector3; + applyMatrix4(matrix: Matrix4, optionalNormalMatrix?: Matrix3): Plane; + translate(offset: Vector3): Plane; + equals(plane: Plane): boolean; + } + + /** + * Implementation of a quaternion. This is used for rotating things without incurring in the dreaded gimbal lock issue, amongst other advantages. + * + * @example + * var quaternion = new THREE.Quaternion(); + * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); + * var vector = new THREE.Vector3( 1, 0, 0 ); + * vector.applyQuaternion( quaternion ); + */ + export class Quaternion { + /** + * @param x x coordinate + * @param y y coordinate + * @param z z coordinate + * @param w w coordinate + */ + constructor(x?: number, y?: number, z?: number, w?: number); + + x: number; + y: number; + z: number; + w: number; + + /** + * Sets values of this quaternion. + */ + set(x: number, y: number, z: number, w: number): Quaternion; + + /** + * Clones this quaternion. + */ + clone(): Quaternion; + + /** + * Copies values of q to this quaternion. + */ + copy(q: Quaternion): Quaternion; + + /** + * Sets this quaternion from rotation specified by Euler angles. + */ + setFromEuler(euler: Euler, update?: boolean): Quaternion; + + /** + * Sets this quaternion from rotation specified by axis and angle. + * Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm. + * Axis have to be normalized, angle is in radians. + */ + setFromAxisAngle(axis: Vector3, angle: number): Quaternion; + + /** + * Sets this quaternion from rotation component of m. Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm. + */ + setFromRotationMatrix(m: Matrix4): Quaternion; + setFromUnitVectors(vFrom: Vector3, vTo: Vector3): Quaternion; + /** + * Inverts this quaternion. + */ + inverse(): Quaternion; + + conjugate(): Quaternion; + dot(v: Vector3): number; + lengthSq(): number; + + /** + * Computes length of this quaternion. + */ + length(): number; + + /** + * Normalizes this quaternion. + */ + normalize(): Quaternion; + + /** + * Multiplies this quaternion by b. + */ + multiply(q: Quaternion): Quaternion; + + /** + * Sets this quaternion to a x b + * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm. + */ + multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; + + /** + * Deprecated. Use Vector3.applyQuaternion instead + */ + multiplyVector3(vector: Vector3): Vector3; + slerp(qb: Quaternion, t: number): Quaternion; + equals(v: Quaternion): boolean; + fromArray(n: number[]): Quaternion; + toArray(): number[]; + + fromArray(xyzw: number[], offset?: number): Quaternion; + toArray(xyzw?: number[], offset?: number): number[]; + + onChange: () => void; + + /** + * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/. + */ + static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: number): Quaternion; + } + + export class Ray { + constructor(origin?: Vector3, direction?: Vector3); + + origin: Vector3; + direction: Vector3; + + set(origin: Vector3, direction: Vector3): Ray; + clone(): Ray; + copy(ray: Ray): Ray; + at(t: number, optionalTarget?: Vector3): Vector3; + recast(t: number): Ray; + closestPointToPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + distanceToPoint(point: Vector3): number; + distanceSqToPoint(point: Vector3): number; + distanceSqToSegment(v0: Vector3, v1: Vector3, optionalPointOnRay?: Vector3, optionalPointOnSegment?: Vector3): number; + isIntersectionSphere(sphere: Sphere): boolean; + intersectSphere(sphere: Sphere, optionalTarget?: Vector3): Vector3; + isIntersectionPlane(plane: Plane): boolean; + distanceToPlane(plane: Plane): number; + intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; + isIntersectionBox(box: Box3): boolean; + intersectBox(box: Box3, optionalTarget?: Vector3): Vector3; + intersectTriangle(a: Vector3, b: Vector3, c: Vector3, backfaceCulling: boolean, optionalTarget?: Vector3): Vector3; + applyMatrix4(matrix4: Matrix4): Ray; + equals(ray: Ray): boolean; + } + + export class Sphere { + constructor(center?: Vector3, radius?: number); + + center: Vector3; + radius: number; + + set(center: Vector3, radius: number): Sphere; + setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; + clone(): Sphere; + copy(sphere: Sphere): Sphere; + empty(): boolean; + containsPoint(point: Vector3): boolean; + distanceToPoint(point: Vector3): number; + intersectsSphere(sphere: Sphere): boolean; + clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + getBoundingBox(optionalTarget?: Box3): Box3; + applyMatrix4(matrix: Matrix4): Sphere; + translate(offset: Vector3): Sphere; + equals(sphere: Sphere): boolean; + } + + export interface SplineControlPoint { + x: number; + y: number; + z: number; + } + + /** + * Represents a spline. + * + * @see src/math/Spline.js + */ + export class Spline { + /** + * Initialises the spline with points, which are the places through which the spline will go. + */ + constructor(points: SplineControlPoint[]); + + points: SplineControlPoint[]; + + /** + * Initialises using the data in the array as a series of points. Each value in a must be another array with three values, where a[n] is v, the value for the nth point, and v[0], v[1] and v[2] are the x, y and z coordinates of that point n, respectively. + * + * @param a array of triplets containing x, y, z coordinates + */ + initFromArray(a: number[][]): void; + + /** + * Return the interpolated point at k. + * + * @param k point index + */ + getPoint(k: number): SplineControlPoint; + + /** + * Returns an array with triplets of x, y, z coordinates that correspond to the current control points. + */ + getControlPointsArray(): number[][]; + + /** + * Returns the length of the spline when using nSubDivisions. + * @param nSubDivisions number of subdivisions between control points. Default is 100. + */ + getLength(nSubDivisions?: number): { chunks: number[]; total: number; }; + + /** + * Modifies the spline so that it looks similar to the original but has its points distributed in such way that moving along the spline it's done at a more or less constant speed. The points should also appear more uniformly spread along the curve. + * This is done by resampling the original spline, with the density of sampling controlled by samplingCoef. Here it's interesting to note that denser sampling is not necessarily better: if sampling is too high, you may get weird kinks in curvature. + * + * @param samplingCoef how many intermediate values to use between spline points + */ + reparametrizeByArcLength(samplingCoef: number): void; + } + + class Triangle { + constructor(a?: Vector3, b?: Vector3, c?: Vector3); + + a: Vector3; + b: Vector3; + c: Vector3; + + set(a: Vector3, b: Vector3, c: Vector3): Triangle; + setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; + clone(): Triangle; + copy(triangle: Triangle): Triangle; + area(): number; + midpoint(optionalTarget?: Vector3): Vector3; + normal(optionalTarget?: Vector3): Vector3; + plane(optionalTarget?: Vector3): Plane; + barycoordFromPoint(point: Vector3, optionalTarget?: Vector3): Vector3; + containsPoint(point: Vector3): boolean; + equals(triangle: Triangle): boolean; + + static normal(a: Vector3, b: Vector3, c: Vector3, optionalTarget?: Vector3): Vector3; + static barycoordFromPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3, optionalTarget: Vector3): Vector3; + static containsPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3): boolean; + } + + + /** + * ( interface Vector<T> ) + * + * Abstract interface of Vector2, Vector3 and Vector4. + * Currently the members of Vector is NOT type safe because it accepts different typed vectors. + * Those definitions will be changed when TypeScript innovates Generics to be type safe. + * + * @example + * var v:THREE.Vector = new THREE.Vector3(); + * v.addVectors(new THREE.Vector2(0, 1), new THREE.Vector2(2, 3)); // invalid but compiled successfully + */ + export interface Vector { + setComponent(index: number, value: number): void; + + getComponent(index: number): number; + + /** + * copy(v:T):T; + */ + copy(v: Vector): Vector; + + /** + * add(v:T):T; + */ + add(v: Vector): Vector; + + /** + * addVectors(a:T, b:T):T; + */ + addVectors(a: Vector, b: Vector): Vector; + + /** + * sub(v:T):T; + */ + sub(v: Vector): Vector; + + /** + * subVectors(a:T, b:T):T; + */ + subVectors(a: Vector, b: Vector): Vector; + + /** + * multiplyScalar(s:number):T; + */ + multiplyScalar(s: number): Vector; + + /** + * divideScalar(s:number):T; + */ + divideScalar(s: number): Vector; + + /** + * negate():T; + */ + negate(): Vector; + + /** + * dot(v:T):T; + */ + dot(v: Vector): number; + + /** + * lengthSq():number; + */ + lengthSq(): number; + + /** + * length():number; + */ + length(): number; + + /** + * normalize():T; + */ + normalize(): Vector; + + /** + * NOTE: Vector4 doesn't have the property. + * + * distanceTo(v:T):number; + */ + distanceTo?(v: Vector): number; + + /** + * NOTE: Vector4 doesn't have the property. + * + * distanceToSquared(v:T):number; + */ + distanceToSquared?(v: Vector): number; + + /** + * setLength(l:number):T; + */ + setLength(l: number): Vector; + + /** + * lerp(v:T, alpha:number):T; + */ + lerp(v: Vector, alpha: number): Vector; + + /** + * equals(v:T):boolean; + */ + equals(v: Vector): boolean; + + /** + * clone():T; + */ + clone(): Vector; + } + + /** + * 2D vector. + * + * ( class Vector2 implements Vector ) + */ + export class Vector2 implements Vector { + constructor(x?: number, y?: number); + + x: number; + y: number; + + width: number; + height: number; + + /** + * Sets value of this vector. + */ + set(x: number, y: number): Vector2; + + /** + * Sets X component of this vector. + */ + setX(x: number): Vector2; + + /** + * Sets Y component of this vector. + */ + setY(y: number): Vector2; + + /** + * Sets a component of this vector. + */ + setComponent(index: number, value: number): void; + + /** + * Gets a component of this vector. + */ + getComponent(index: number): number; + /** + * Clones this vector. + */ + clone(): Vector2; + /** + * Copies value of v to this vector. + */ + copy(v: Vector2): Vector2; + + /** + * Adds v to this vector. + */ + add(v: Vector2): Vector2; + + /** + * Sets this vector to a + b. + */ + addScalar(s: number): Vector2; + addVectors(a: Vector2, b: Vector2): Vector2; + addScaledVector( v: Vector2, s: number ): Vector2; + /** + * Subtracts v from this vector. + */ + sub(v: Vector2): Vector2; + + /** + * Sets this vector to a - b. + */ + subVectors(a: Vector2, b: Vector2): Vector2; + + multiply(v: Vector2): Vector2; + /** + * Multiplies this vector by scalar s. + */ + multiplyScalar(scalar: number): Vector2; + + divide(v: Vector2): Vector2; + /** + * Divides this vector by scalar s. + * Set vector to ( 0, 0 ) if s == 0. + */ + divideScalar(s: number): Vector2; + + min(v: Vector2): Vector2; + + max(v: Vector2): Vector2; + clamp(min: Vector2, max: Vector2): Vector2; + clampScalar(min: number, max: number): Vector2; + clampLength(min: number, max: number): Vector2; + floor(): Vector2; + ceil(): Vector2; + round(): Vector2; + roundToZero(): Vector2; + + /** + * Inverts this vector. + */ + negate(): Vector2; + + /** + * Computes dot product of this vector and v. + */ + dot(v: Vector2): number; + + /** + * Computes squared length of this vector. + */ + lengthSq(): number; + + /** + * Computes length of this vector. + */ + length(): number; + lengthManhattan(): number; + + /** + * Normalizes this vector. + */ + normalize(): Vector2; + + /** + * Computes distance of this vector to v. + */ + distanceTo(v: Vector2): number; + + /** + * Computes squared distance of this vector to v. + */ + distanceToSquared(v: Vector2): number; + + /** + * Normalizes this vector and multiplies it by l. + */ + setLength(length: number): Vector2; + + lerp(v: Vector2, alpha: number): Vector2; + + lerpVectors(v1: Vector2, v2: Vector2, alpha: number): Vector2; + + /** + * Checks for strict equality of this vector and v. + */ + equals(v: Vector2): boolean; + + fromArray(xy: number[], offset?: number): Vector2; + + toArray(xy?: number[], offset?: number): number[]; + + fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector2; + + rotateAround( center: Vector2, angle: number ): Vector2; + } + + /** + * 3D vector. + * + * @example + * var a = new THREE.Vector3( 1, 0, 0 ); + * var b = new THREE.Vector3( 0, 1, 0 ); + * var c = new THREE.Vector3(); + * c.crossVectors( a, b ); + * + * @see src/math/Vector3.js + * + * ( class Vector3 implements Vector ) + */ + export class Vector3 implements Vector { + + constructor(x?: number, y?: number, z?: number); + + x: number; + y: number; + z: number; + + /** + * Sets value of this vector. + */ + set(x: number, y: number, z: number): Vector3; + + /** + * Sets x value of this vector. + */ + setX(x: number): Vector3; + + /** + * Sets y value of this vector. + */ + setY(y: number): Vector3; + + /** + * Sets z value of this vector. + */ + setZ(z: number): Vector3; + + setComponent(index: number, value: number): void; + getComponent(index: number): number; + /** + * Clones this vector. + */ + clone(): Vector3; + /** + * Copies value of v to this vector. + */ + copy(v: Vector3): Vector3; + + /** + * Adds v to this vector. + */ + add(a: Vector3): Vector3; + addScalar(s: number): Vector3; + addScaledVector(v: Vector3, s: number): Vector3; + + /** + * Sets this vector to a + b. + */ + addVectors(a: Vector3, b: Vector3): Vector3; + addScaledVector( v: Vector3, s: number ): Vector3; + + /** + * Subtracts v from this vector. + */ + sub(a: Vector3): Vector3; + + subScalar( s: number ): Vector3; + + /** + * Sets this vector to a - b. + */ + subVectors(a: Vector3, b: Vector3): Vector3; + + multiply(v: Vector3): Vector3; + /** + * Multiplies this vector by scalar s. + */ + multiplyScalar(s: number): Vector3; + multiplyVectors(a: Vector3, b: Vector3): Vector3; + applyEuler(euler: Euler): Vector3; + applyAxisAngle(axis: Vector3, angle: number): Vector3; + applyMatrix3(m: Matrix3): Vector3; + applyMatrix4(m: Matrix4): Vector3; + applyProjection(m: Matrix4): Vector3; + applyQuaternion(q: Quaternion): Vector3; + project(camrea: Camera): Vector3; + unproject(camera: Camera): Vector3; + transformDirection(m: Matrix4): Vector3; + divide(v: Vector3): Vector3; + + /** + * Divides this vector by scalar s. + * Set vector to ( 0, 0, 0 ) if s == 0. + */ + divideScalar(s: number): Vector3; + min(v: Vector3): Vector3; + max(v: Vector3): Vector3; + clamp(min: Vector3, max: Vector3): Vector3; + clampScalar(min: number, max: number): Vector3; + clampLength(min: number, max: number): Vector3; + floor(): Vector3; + ceil(): Vector3; + round(): Vector3; + roundToZero(): Vector3; + + /** + * Inverts this vector. + */ + negate(): Vector3; + + /** + * Computes dot product of this vector and v. + */ + dot(v: Vector3): number; + + /** + * Computes squared length of this vector. + */ + lengthSq(): number; + + /** + * Computes length of this vector. + */ + length(): number; + + /** + * Computes Manhattan length of this vector. + * http://en.wikipedia.org/wiki/Taxicab_geometry + */ + lengthManhattan(): number; + + /** + * Normalizes this vector. + */ + normalize(): Vector3; + + /** + * Normalizes this vector and multiplies it by l. + */ + setLength(l: number): Vector3; + lerp(v: Vector3, alpha: number): Vector3; + + lerpVectors(v1: Vector3, v2: Vector3, alpha: number): Vector3; + + /** + * Sets this vector to cross product of itself and v. + */ + cross(a: Vector3): Vector3; + + /** + * Sets this vector to cross product of a and b. + */ + crossVectors(a: Vector3, b: Vector3): Vector3; + projectOnVector(v: Vector3): Vector3; + projectOnPlane(planeNormal: Vector3): Vector3; + reflect(vector: Vector3): Vector3; + angleTo(v: Vector3): number; + + /** + * Computes distance of this vector to v. + */ + distanceTo(v: Vector3): number; + + /** + * Computes squared distance of this vector to v. + */ + distanceToSquared(v: Vector3): number; + + setFromMatrixPosition(m: Matrix4): Vector3; + setFromMatrixScale(m: Matrix4): Vector3; + setFromMatrixColumn(index: number, matrix: Matrix4): Vector3; + + /** + * Checks for strict equality of this vector and v. + */ + equals(v: Vector3): boolean; + + fromArray(xyz: number[], offset?: number): Vector3; + + toArray(xyz?: number[], offset?: number): number[]; + + fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector3; + } + + /** + * 4D vector. + * + * ( class Vector4 implements Vector ) + */ + export class Vector4 implements Vector { + constructor(x?: number, y?: number, z?: number, w?: number); + x: number; + y: number; + z: number; + w: number; + + /** + * Sets value of this vector. + */ + set(x: number, y: number, z: number, w: number): Vector4; + + /** + * Sets X component of this vector. + */ + setX(x: number): Vector4; + + /** + * Sets Y component of this vector. + */ + setY(y: number): Vector4; + + /** + * Sets Z component of this vector. + */ + setZ(z: number): Vector4; + + /** + * Sets w component of this vector. + */ + setW(w: number): Vector4; + + setComponent(index: number, value: number): void; + getComponent(index: number): number; + /** + * Clones this vector. + */ + clone(): Vector4; + /** + * Copies value of v to this vector. + */ + copy(v: Vector4): Vector4; + + /** + * Adds v to this vector. + */ + add(v: Vector4): Vector4; + addScalar(s: number): Vector4; + + /** + * Sets this vector to a + b. + */ + addVectors(a: Vector4, b: Vector4): Vector4; + addScaledVector( v: Vector4, s: number ): Vector4; + /** + * Subtracts v from this vector. + */ + sub(v: Vector4): Vector4; + + subScalar(s: number): Vector4; + + /** + * Sets this vector to a - b. + */ + subVectors(a: Vector4, b: Vector4): Vector4; + + /** + * Multiplies this vector by scalar s. + */ + multiplyScalar(s: number): Vector4; + applyMatrix4(m: Matrix4): Vector4; + + /** + * Divides this vector by scalar s. + * Set vector to ( 0, 0, 0 ) if s == 0. + */ + divideScalar(s: number): Vector4; + + /** + * http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm + * @param q is assumed to be normalized + */ + setAxisAngleFromQuaternion(q: Quaternion): Vector4; + + /** + * http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm + * @param m assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + */ + setAxisAngleFromRotationMatrix(m: Matrix4): Vector4; + + min(v: Vector4): Vector4; + max(v: Vector4): Vector4; + clamp(min: Vector4, max: Vector4): Vector4; + clampScalar(min: number, max: number): Vector4; + floor(): Vector4; + ceil(): Vector4; + round(): Vector4; + roundToZero(): Vector4; + + /** + * Inverts this vector. + */ + negate(): Vector4; + + /** + * Computes dot product of this vector and v. + */ + dot(v: Vector4): number; + + /** + * Computes squared length of this vector. + */ + lengthSq(): number; + + /** + * Computes length of this vector. + */ + length(): number; + lengthManhattan(): number; + + /** + * Normalizes this vector. + */ + normalize(): Vector4; + /** + * Normalizes this vector and multiplies it by l. + */ + setLength(length: number): Vector4; + + /** + * Linearly interpolate between this vector and v with alpha factor. + */ + lerp(v: Vector4, alpha: number): Vector4; + + lerpVectors(v1: Vector4, v2: Vector4, alpha: number): Vector4; + + /** + * Checks for strict equality of this vector and v. + */ + equals(v: Vector4): boolean; + + fromArray(xyzw: number[], offset?: number): Vector4; + + toArray(xyzw?: number[], offset?: number): number[]; + + fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector4; + } + + // Objects ////////////////////////////////////////////////////////////////////////////////// + + export class Bone extends Object3D { + constructor(skin: SkinnedMesh); + + skin: SkinnedMesh; + + clone(): Bone; + copy(source: Bone): Bone; + } + + export class Group extends Object3D { + constructor(); + } + + export class LOD extends Object3D { + constructor(); + + levels: any[]; + + addLevel(object: Object3D, distance?: number): void; + getObjectForDistance(distance: number): Object3D; + raycast(raycaster: Raycaster, intersects: any): void; + update(camera: Camera): void; + + clone(): LOD; + copy(source: LOD): LOD; + toJSON(meta: any): any; + } + + export interface LensFlareProperty { + texture: Texture; // Texture + size: number; // size in pixels (-1 = use texture.width) + distance: number; // distance (0-1) from light source (0=at light source) + x: number; + y: number; + z: number; // screen position (-1 => 1) z = 0 is ontop z = 1 is back + scale: number; // scale + rotation: number; // rotation + opacity: number; // opacity + color: Color; // color + blending: Blending; + } + + export class LensFlare extends Object3D { + constructor(texture?: Texture, size?: number, distance?: number, blending?: Blending, color?: Color); + + lensFlares: LensFlareProperty[]; + positionScreen: Vector3; + customUpdateCallback: (object: LensFlare) => void; + + add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; + add(obj: Object3D): void; + + updateLensFlares(): void; + + clone(): LensFlare; + copy(source: LensFlare): LensFlare; + } + + export class Line extends Object3D { + constructor( + geometry?: Geometry | BufferGeometry, + material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, + mode?: number + ); + + geometry: Geometry|BufferGeometry; + material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial + + raycast(raycaster: Raycaster, intersects: any): void; + clone(): Line; + copy(source: Line): Line; + } + + export class LineSegments extends Line { + constructor( + geometry?: Geometry | BufferGeometry, + material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, + mode?: number + ); + + clone(): LineSegments; + copy(source: LineSegments): LineSegments; + } + + enum LineMode{} + var LineStrip: LineMode; + var LinePieces: LineMode; + + export class Mesh extends Object3D { + constructor(geometry?: Geometry, material?: Material); + constructor(geometry?: BufferGeometry, material?: Material); + + geometry: Geometry|BufferGeometry; + material: Material; + + updateMorphTargets(): void; + getMorphTargetIndexByName(name: string): number; + raycast(raycaster: Raycaster, intersects: any): void; + clone(): Mesh; + copy(source: Mesh): Mesh; + } + + /** + * A class for displaying particles in the form of variable size points. For example, if using the WebGLRenderer, the particles are displayed using GL_POINTS. + * + * @see src/objects/ParticleSystem.js + */ + export class Points extends Object3D { + + /** + * @param geometry An instance of Geometry. + * @param material An instance of Material (optional). + */ + constructor( + geometry: Geometry | BufferGeometry, + material?: PointsMaterial | ShaderMaterial + ); + + /** + * An instance of Geometry, where each vertex designates the position of a particle in the system. + */ + geometry: Geometry; + + /** + * An instance of Material, defining the object's appearance. Default is a ParticleBasicMaterial with randomised colour. + */ + material: Material; + + raycast(raycaster: Raycaster, intersects: any): void; + clone(): Points; + copy(source: Points): Points; + } + + export class Skeleton { + constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); + + useVertexTexture: boolean; + identityMatrix: Matrix4; + bones: Bone[]; + boneTextureWidth: number; + boneTextureHeight: number; + boneMatrices: Float32Array; + boneTexture: DataTexture; + boneInverses: Matrix4[]; + + calculateInverses(bone: Bone): void; + pose(): void; + update(): void; + clone(): Skeleton; + + } + + export class SkinnedMesh extends Mesh { + constructor(geometry?: Geometry|BufferGeometry, material?: MeshBasicMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: MeshDepthMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: MeshFaceMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: MeshLambertMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: MeshNormalMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: ShaderMaterial, useVertexTexture?: boolean); + + bindMode: string; + bindMatrix: Matrix4; + bindMatrixInverse: Matrix4; + + bind( skeleton: Skeleton, bindMatrix?: Matrix4 ): void; + pose(): void; + normalizeSkinWeights(): void; + updateMatrixWorld(force?: boolean): void; + clone(): SkinnedMesh; + copy(source?: SkinnedMesh): SkinnedMesh; + + skeleton: Skeleton; + } + + export class Sprite extends Object3D { + constructor(material?: Material); + + geometry: BufferGeometry; + material: SpriteMaterial; + + raycast(raycaster: Raycaster, intersects: any): void; + clone(): Sprite; + copy(source?: Sprite): Sprite; + } + + + // Renderers ////////////////////////////////////////////////////////////////////////////////// + + export interface Renderer { + render(scene: Scene, camera: Camera): void; + setSize(width:number, height:number, updateStyle?:boolean): void; + domElement: HTMLCanvasElement; + } + + export interface WebGLRendererParameters { + /** + * A Canvas where the renderer draws its output. + */ + canvas?: HTMLCanvasElement; + + /** + * shader precision. Can be "highp", "mediump" or "lowp". + */ + precision?: string; + + /** + * default is true. + */ + alpha?: boolean; + + /** + * default is true. + */ + premultipliedAlpha?: boolean; + + /** + * default is false. + */ + antialias?: boolean; + + /** + * default is true. + */ + stencil?: boolean; + + /** + * default is false. + */ + preserveDrawingBuffer?: boolean; + + /** + * default is 0x000000. + */ + clearColor?: number; + + /** + * default is 0. + */ + clearAlpha?: number; + + devicePixelRatio?: number; + + /** + * default is false. + */ + logarithmicDepthBuffer?: boolean; + } + + + /** + * The WebGL renderer displays your beautifully crafted scenes using WebGL, if your device supports it. + * This renderer has way better performance than CanvasRenderer. + * + * @see src/renderers/WebGLRenderer.js + */ + export class WebGLRenderer implements Renderer { + /** + * parameters is an optional object with properties defining the renderer's behaviour. The constructor also accepts no parameters at all. In all cases, it will assume sane defaults when parameters are missing. + */ + constructor(parameters?: WebGLRendererParameters); + + /** + * A Canvas where the renderer draws its output. + * This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page. + */ + domElement: HTMLCanvasElement; + + /** + * The HTML5 Canvas's 'webgl' context obtained from the canvas where the renderer will draw. + */ + context: WebGLRenderingContext; + + /** + * Defines whether the renderer should automatically clear its output before rendering. + */ + autoClear: boolean; + + /** + * If autoClear is true, defines whether the renderer should clear the color buffer. Default is true. + */ + autoClearColor: boolean; + + /** + * If autoClear is true, defines whether the renderer should clear the depth buffer. Default is true. + */ + autoClearDepth: boolean; + + /** + * If autoClear is true, defines whether the renderer should clear the stencil buffer. Default is true. + */ + autoClearStencil: boolean; + + /** + * Defines whether the renderer should sort objects. Default is true. + */ + sortObjects: boolean; + + extensions: WebGLExtensions; + + gammaFactor: number; + + /** + * Default is false. + */ + gammaInput: boolean; + + /** + * Default is false. + */ + gammaOutput: boolean; + + /** + * Default is false. + */ + shadowMapEnabled: boolean; + + /** + * Defines shadow map type (unfiltered, percentage close filtering, percentage close filtering with bilinear filtering in shader) + * Options are THREE.BasicShadowMap, THREE.PCFShadowMap, THREE.PCFSoftShadowMap. Default is THREE.PCFShadowMap. + */ + shadowMapType: ShadowMapType; + + /** + * Default is true + */ + shadowMapCullFace: CullFace; + + /** + * Default is false. + */ + shadowMapDebug: boolean; + + /** + * Default is 8. + */ + maxMorphTargets: number; + + /** + * Default is 4. + */ + maxMorphNormals: number; + + /** + * Default is true. + */ + autoScaleCubemaps: boolean; + + /** + * An object with a series of statistical information about the graphics board memory and the rendering process. Useful for debugging or just for the sake of curiosity. The object contains the following fields: + */ + info: { + memory: { + programs: number; + geometries: number; + textures: number; + }; + render: { + calls: number; + vertices: number; + faces: number; + points: number; + }; + }; + + shadowMap: WebGLShadowMapInstance; + + /** + * Return the WebGL context. + */ + getContext(): WebGLRenderingContext; + + forceContextLoss(): void; + + capabilities: WebGLCapabilities; + + /** Deprecated, use capabilities instead */ + supportsVertexTextures(): boolean; + supportsFloatTextures(): boolean; + supportsStandardDerivatives(): boolean; + supportsCompressedTextureS3TC(): boolean; + supportsCompressedTexturePVRTC(): boolean; + supportsBlendMinMax(): boolean; + getPrecision(): string; + + getMaxAnisotropy(): number; + getPixelRatio(): number; + setPixelRatio(value: number): void; + + getSize(): { width: number; height: number; }; + + /** + * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). + */ + setSize(width: number, height: number, updateStyle?: boolean): void; + + /** + * Sets the viewport to render from (x, y) to (x + width, y + height). + */ + setViewport(x?: number, y?: number, width?: number, height?: number): void; + + /** + * Sets the scissor area from (x, y) to (x + width, y + height). + */ + setScissor(x: number, y: number, width: number, height: number): void; + + /** + * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. + */ + enableScissorTest(enable: boolean): void; + + /** + * Sets the clear color, using color for the color and alpha for the opacity. + */ + setClearColor(color: Color, alpha?: number): void; + setClearColor(color: string, alpha?: number): void; + setClearColor(color: number, alpha?: number): void; + + setClearAlpha(alpha: number): void; + + /** + * Sets the clear color, using hex for the color and alpha for the opacity. + * + * @example + * // Creates a renderer with black background + * var renderer = new THREE.WebGLRenderer(); + * renderer.setSize(200, 100); + * renderer.setClearColorHex(0x000000, 1); + */ + setClearColorHex(hex: number, alpha: number): void; + + /** + * Returns a THREE.Color instance with the current clear color. + */ + getClearColor(): Color; + + /** + * Returns a float with the current clear alpha. Ranges from 0 to 1. + */ + getClearAlpha(): number; + + /** + * Tells the renderer to clear its color, depth or stencil drawing buffer(s). + * Arguments default to true + */ + clear(color?: boolean, depth?: boolean, stencil?: boolean): void; + + clearColor(): void; + clearDepth(): void; + clearStencil(): void; + clearTarget(renderTarget:WebGLRenderTarget, color: boolean, depth: boolean, stencil: boolean): void; + resetGLState(): void; + dispose(): void; + + /** + * Tells the shadow map plugin to update using the passed scene and camera parameters. + * + * @param scene an instance of Scene + * @param camera — an instance of Camera + */ + updateShadowMap(scene: Scene, camera: Camera): void; + + renderBufferImmediate(object: Object3D, program: Object, material: Material): void; + + renderBufferDirect(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; + + renderBuffer(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; + + /** + * Render a scene using a camera. + * The render is done to the renderTarget (if specified) or to the canvas as usual. + * If forceClear is true, the canvas will be cleared before rendering, even if the renderer's autoClear property is false. + */ + render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; + renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; + + /** + * Used for setting the gl frontFace, cullFace states in the GPU, thus enabling/disabling face culling when rendering. + * If cullFace is false, culling will be disabled. + * @param cullFace "back", "front", "front_and_back", or false. + * @param frontFace "ccw" or "cw + */ + setFaceCulling(cullFace?: CullFace, frontFace?: FrontFaceDirection): void; + setMaterialFaces(material: Material): void; + setDepthTest(depthTest: boolean): void; + setDepthWrite(depthWrite: boolean): void; + setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; + uploadTexture(texture: Texture): void; + setTexture(texture: Texture, slot: number): void; + setRenderTarget(renderTarget: RenderTarget): void; + readRenderTargetPixels( renderTarget: RenderTarget, x: number, y: number, width: number, height: number, buffer: any ): void; + } + + export interface RenderTarget { + } + + export interface WebGLRenderTargetOptions { + wrapS?: Wrapping; + wrapT?: Wrapping; + magFilter?: TextureFilter; + minFilter?: TextureFilter; + anisotropy?: number; // 1; + format?: number; // RGBAFormat; + type?: TextureDataType; // UnsignedByteType; + depthBuffer?: boolean; // true; + stencilBuffer?: boolean; // true; + } + + export class WebGLRenderTarget implements RenderTarget { + constructor(width: number, height: number, options?: WebGLRenderTargetOptions); + + uuid: string; + width: number; + height: number; + wrapS: Wrapping; + wrapT: Wrapping; + magFilter: TextureFilter; + minFilter: TextureFilter; + anisotropy: number; + offset: Vector2; + repeat: Vector2; + format: number; + type: number; + depthBuffer: boolean; + stencilBuffer: boolean; + generateMipmaps: boolean; + shareDepthFrom: any; + + setSize(width: number, height: number): void; + clone(): WebGLRenderTarget; + copy(source: WebGLRenderTarget): WebGLRenderTarget; + dispose(): void; + + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } + + export class WebGLRenderTargetCube extends WebGLRenderTarget { + constructor(width: number, height: number, options?: WebGLRenderTargetOptions); + + activeCubeFace: number; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5 + } + + // Renderers / Shaders ///////////////////////////////////////////////////////////////////// + export interface ShaderChunk { + [name: string]: string; + + common: string; + + alphamap_fragment: string; + alphamap_pars_fragment: string; + alphatest_fragment: string; + aomap_fragment: string; + aomap_pars_fragment: string; + begin_vertex: string; + beginnormal_vertex: string; + bumpmap_pars_fragment: string; + color_fragment: string; + color_pars_fragment: string; + color_pars_vertex: string; + color_vertex: string; + defaultnormal_vertex: string; + displacementmap_pars_vertex: string; + displacementmap_vertex: string; + emissivemap_fragment: string; + emissivemap_pars_fragment: string; + envmap_fragment: string; + envmap_pars_fragment: string; + envmap_pars_vertex: string; + envmap_vertex: string; + fog_fragment: string; + fog_pars_fragment: string; + hemilight_fragment: string; + lightmap_fragment: string; + lightmap_pars_fragment: string; + lights_lambert_pars_vertex: string; + lights_lambert_vertex: string; + lights_phong_fragment: string; + lights_phong_pars_fragment: string; + lights_phong_pars_vertex: string; + lights_phong_vertex: string; + linear_to_gamma_fragment: string; + logdepthbuf_fragment: string; + logdepthbuf_pars_fragment: string; + logdepthbuf_pars_vertex: string; + logdepthbuf_vertex: string; + map_fragment: string; + map_pars_fragment: string; + map_particle_fragment: string; + map_particle_pars_fragment: string; + morphnormal_vertex: string; + morphtarget_pars_vertex: string; + morphtarget_vertex: string; + normal_phong_fragment: string; + normalmap_pars_fragment: string; + project_vertex: string; + shadowmap_fragment: string; + shadowmap_pars_fragment: string; + shadowmap_pars_vertex: string; + shadowmap_vertex: string; + skinbase_vertex: string; + skinning_pars_vertex: string; + skinning_vertex: string; + skinnormal_vertex: string; + specularmap_fragment: string; + specularmap_pars_fragment: string; + uv2_pars_fragment: string; + uv2_pars_vertex: string; + uv2_vertex: string; + uv_pars_fragment: string; + uv_pars_vertex: string; + uv_vertex: string; + worldpos_vertex: string; + } + + export var ShaderChunk: ShaderChunk; + + export interface Shader { + uniforms: any; + vertexShader: string; + fragmentShader: string; + } + + export var ShaderLib: { + [name: string]: Shader; + basic: Shader; + lambert: Shader; + phong: Shader; + particle_basic: Shader; + dashed: Shader; + depth: Shader; + normal: Shader; + normalmap: Shader; + cube: Shader; + equirect: Shader; + depthRGBA: Shader; + }; + + export var UniformsLib: { + common: any; + aomap: any; + lightmap: any; + emissivemap: any; + bumpmap: any; + normalmap: any; + displacementmap: any; + fog: any; + lights: any; + points: any; + shadowmap: any; + }; + + export var UniformsUtils: { + merge(uniforms: any[]): any; + clone(uniforms_src: any): any; + }; + + // Renderers / WebGL ///////////////////////////////////////////////////////////////////// + export class WebGLBufferRenderer{ + constructor(_gl: any, extensions: any, _infoRender: any); // WebGLRenderingContext + + setMode( value: any ): void; + render( start: any, count: any ): void; + renderInstances( geometry: any ): void; + } + + export class WebGLCapabilities{ + constructor(gl: any, extensions: any, parameters: any); // WebGLRenderingContext + + getMaxPrecision: any; + precision: any; + maxTextures: any; + maxVertexTextures: any; + maxTextureSize: any; + maxCubemapSize: any; + maxAttributes: any; + maxVertexUniforms: any; + maxVaryings: any; + maxFragmentUniforms: any; + vertexTextures: any; + floatFragmentTextures: any; + floatVertexTextures: any; + } + + export class WebGLExtensions{ + constructor(gl: any); // WebGLRenderingContext + + get(name: string): any; + } + + interface WebGLGeometriesInstance { + get( object: any ): any; + } + interface WebGLGeometriesStatic{ + new (gl: any, properties: any, info: any): WebGLGeometriesInstance; + } + export var WebGLGeometries: WebGLGeometriesStatic; + + + interface WebGLIndexedBufferRendererInstance { + setMode( value: any ): void; + setIndex( index: any ): void; + render( start: any, count: any ): void; + renderInstances( geometry: any ): void; + } + interface WebGLIndexedBufferRendererStatic{ + new (gl: any, properties: any, info: any): WebGLIndexedBufferRendererInstance; + } + export var WebGLIndexedBufferRenderer: WebGLIndexedBufferRendererStatic; + + + interface WebGLObjectsInstance { + getAttributeBuffer( attribute: any ): any; + getWireframeAttribute(geometry: any): any; + update(object: any): void; + } + interface WebGLObjectsStatic{ + new (gl: any, properties: any, info: any): WebGLObjectsInstance; + } + export var WebGLObjects: WebGLObjectsStatic; + + export class WebGLProgram{ + constructor(renderer: WebGLRenderer, code: string, material: ShaderMaterial, parameters: WebGLRendererParameters); + + getUniforms(): any; + getAttributes(): any; + + /** Deprecated, use getUniforms */ + uniforms: any; + /** Deprecated, use getAttributes */ + attributes: any; + + id: number; + code: string; + usedTimes: number; + program: any; + vertexShader: WebGLShader; + fragmentShader: WebGLShader; + } + + interface WebGLProgramsInstance { + getParameters( material: any, lights: any, fog: any, object: any ): any[]; + getProgramCode( material: any, parameters: any ): any; + acquireProgram( material: any, parameters: any, code: any ): any; + releaseProgram( program: any ): void; + } + interface WebGLProgramsStatic{ + new (renderer: WebGLRenderer, capabilities: any): WebGLProgramsInstance; + } + export var WebGLPrograms: WebGLProgramsStatic; + + interface WebGLPropertiesInstance { + get(object: any): any; + delete(object: any): void; + clear(): void; + } + interface WebGLPropertiesStatic{ + new (): WebGLPropertiesInstance; + } + export var WebGLProperties: WebGLPropertiesStatic; + + export class WebGLShader{ + constructor(gl: any, type: string, string: string); + } + + interface WebGLShadowMapInstance{ + enabled: boolean; + autoUpdate: boolean; + needsUpdate: boolean; + type: ShadowMapType; + cullFace: CullFace; + + render( scene: Scene ): void; + } + interface WebGLShadowMapStatic{ + new ( _renderer: Renderer, _lights: any[], _objects: any[] ): WebGLStateInstance; + } + export var WebGLShadowMap: WebGLShadowMapStatic; + + interface WebGLStateInstance{ + init(): void; + initAttributes(): void; + enableAttribute(attribute: string): void; + enableAttributeAndDivisor( attribute: string, meshPerAttribute: any, extension: any ): void; + disableUnusedAttributes(): void; + enable( id: string ): void; + disable( id: string ): void; + getCompressedTextureFormats(): any; + setBlending( blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number ): void; + setDepthFunc( func: Function): void; + setDepthTest( depthTest: number ): void; + setDepthWrite( depthWrite: number ): void; + setColorWrite( colorWrite: number ): void; + setFlipSided( flipSided: number ): void; + setLineWidth( width: number ): void; + setPolygonOffset(polygonoffset: number, factor: number, units: number): void; + setScissorTest( scissorTest: boolean ): void; + activeTexture( webglSlot: any ): void; + bindTexture( webglType: any, webglTexture: any ): void; + compressedTexImage2D(): void; + texImage2D(): void; + reset(): void; + } + interface WebGLStateStatic{ + new ( gl: any, extensions: any, paramThreeToGL: Function ): WebGLStateInstance; + } + export var WebGLState: WebGLStateStatic; + + + // Renderers / WebGL / Plugins ///////////////////////////////////////////////////////////////////// + export interface RendererPlugin { + init(renderer: WebGLRenderer): void; + render(scene: Scene, camera: Camera, currentWidth: number, currentHeight: number): void; + } + + export class LensFlarePlugin implements RendererPlugin { + constructor(); + + init(renderer: Renderer): void; + render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; + } + + export class SpritePlugin implements RendererPlugin { + constructor(); + + init(renderer: Renderer): void; + render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; + } + + // Scenes ///////////////////////////////////////////////////////////////////// + + export interface IFog { + name:string; + color: Color; + clone():IFog; + } + + + /** + * This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance. + */ + export class Fog implements IFog { + constructor(hex: number, near?: number, far?: number); + + name:string; + + /** + * Fog color. + */ + color: Color; + + /** + * The minimum distance to start applying fog. Objects that are less than 'near' units from the active camera won't be affected by fog. + */ + near: number; + + /** + * The maximum distance at which fog stops being calculated and applied. Objects that are more than 'far' units away from the active camera won't be affected by fog. + * Default is 1000. + */ + far: number; + + clone(): Fog; + } + + /** + * This class contains the parameters that define linear fog, i.e., that grows exponentially denser with the distance. + */ + export class FogExp2 implements IFog { + constructor(hex: number|string, density?: number); + + name: string; + color: Color; + + /** + * Defines how fast the fog will grow dense. + * Default is 0.00025. + */ + density: number; + + clone(): FogExp2; + } + + /** + * Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras. + */ + export class Scene extends Object3D { + constructor(); + + /** + * A fog instance defining the type of fog that affects everything rendered in the scene. Default is null. + */ + fog: IFog; + + /** + * If not null, it will force everything in the scene to be rendered with that material. Default is null. + */ + overrideMaterial: Material; + autoUpdate: boolean; + + copy(source: Scene): Scene; + } + + // Textures ///////////////////////////////////////////////////////////////////// + export class CanvasTexture extends Texture { + constructor( + canvas: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + needsUpdate: boolean; + } + + export class CompressedTexture extends Texture { + constructor( + mipmaps: ImageData[], + width: number, + height: number, + format?: PixelFormat, + type?: TextureDataType, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + anisotropy?: number + ); + + image: { width: number; height: number; }; + mipmaps: ImageData[]; + flipY: boolean; + generateMipmaps: boolean; + } + + export class CubeTexture extends Texture { + constructor( + images: any[], // HTMLImageElement or HTMLCanvasElement + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + images: any[]; + + copy(source: CubeTexture): CubeTexture; + } + + export class DataTexture extends Texture { + constructor( + data: ImageData, + width: number, + height: number, + format: PixelFormat, + type: TextureDataType, + mapping: Mapping, + wrapS: Wrapping, + wrapT: Wrapping, + magFilter: TextureFilter, + minFilter: TextureFilter, + anisotropy?: number + ); + + image: { data: ImageData; width: number; height: number; }; + magFilter: TextureFilter; + minFilter: TextureFilter; + flipY: boolean; + generateMipmaps: boolean; + } + + export class Texture { + constructor( + image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + id: number; + uuid: string; + name: string; + sourceFile: string; + image: any; // HTMLImageElement or ImageData ; + mipmaps: ImageData[]; + mapping: Mapping; + wrapS: Wrapping; + wrapT: Wrapping; + magFilter: TextureFilter; + minFilter: TextureFilter; + anisotropy: number; + format: PixelFormat; + type: TextureDataType; + offset: Vector2; + repeat: Vector2; + generateMipmaps: boolean; + premultiplyAlpha: boolean; + flipY: boolean; + unpackAlignment: number; + version: number; + needsUpdate: boolean; + onUpdate: () => void; + static DEFAULT_IMAGE: any; + static DEFAULT_MAPPING: any; + + clone(): Texture; + copy(source: Texture): Texture; + toJSON(meta: any): any; + dispose(): void; + transformUv( uv: Vector ): void; + + // EventDispatcher mixins + addEventListener(type: string, listener: (event: any) => void ): void; + hasEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: any) => void): void; + dispatchEvent(event: { type: string; target: any; }): void; + } + + class VideoTexture extends Texture { + constructor( + video: HTMLVideoElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + generateMipmaps: boolean; + } + + // Extras ///////////////////////////////////////////////////////////////////// + export var CurveUtils: { + tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; + interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; + } + + // deprecated. + export var ImageUtils: { + crossOrigin: string; + + // deprecated. + loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; + + // deprecated. + loadTextureCube(array: string[], mapping?: Mapping, onLoad?: (texture: Texture) => void , onError?: (message: string) => void ): Texture; + + // deprecated. + getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; + + // deprecated. + generateDataTexture(width: number, height: number, color: Color): DataTexture; + }; + + export var SceneUtils: { + createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; + detach(child: Object3D, parent: Object3D, scene: Scene): void; + attach(child: Object3D, scene: Scene, parent: Object3D): void; + }; + + export var ShapeUtils: { + area( contour: number[] ): number; + triangulate( contour: number[], indices: boolean ): number[]; + triangulateShape( contour: number[], holes: any[] ): number[]; + isClockWise( pts: number[] ): boolean; + b2( t: number, p0: number, p1: number, p2: number ): number; + b3( t: number, p0: number, p1: number, p2: number, p3: number ): number; + }; + + // Extras / Audio ///////////////////////////////////////////////////////////////////// + + export class Audio extends Object3D { + constructor(listener: AudioListener); + type: string; + context: AudioContext; + source: AudioBufferSourceNode; + gain: GainNode; + panner: PannerNode; + autoplay: boolean; + startTime: number; + playbackRate: number; + isPlaying: boolean; + + load(file: string): Audio; + play(): void; + pause(): void; + stop(): void; + connect(): void; + disconnect(): void; + setFilter(value: any): void; + getFilter(): any; + setPlaybackRate(value: number): void; + getPlaybackRate(): number; + + setLoop(value: boolean): void; + getLoop(): boolean; + setRefDistance(value: number): void; + getRefDistance(): number; + setRolloffFactor(value: number): void; + getRolloffFactor(): number; + setVolume(value: number): void; + getVolume(): number; + updateMatrixWorld(force?: boolean): void; + } + + export class AudioListener extends Object3D { + constructor(); + + type: string; + context: AudioContext; + + updateMatrixWorld(force?: boolean): void; + } + + // Extras / Core ///////////////////////////////////////////////////////////////////// + + /** + * An extensible curve object which contains methods for interpolation + * class Curve<T extends Vector> + */ + export class Curve { + /** + * Returns a vector for point t of the curve where t is between 0 and 1 + * getPoint(t: number): T; + */ + getPoint(t: number): T; + + /** + * Returns a vector for point at relative position in curve according to arc length + * getPointAt(u: number): T; + */ + getPointAt(u: number):T; + + /** + * Get sequence of points using getPoint( t ) + * getPoints(divisions?: number): T[]; + */ + getPoints(divisions?: number): T[]; + + /** + * Get sequence of equi-spaced points using getPointAt( u ) + * getSpacedPoints(divisions?: number): T[]; + */ + getSpacedPoints(divisions?: number): T[]; + + /** + * Get total curve arc length + */ + getLength(): number; + + /** + * Get list of cumulative segment lengths + */ + getLengths(divisions?: number): number[]; + + /** + * Update the cumlative segment distance cache + */ + updateArcLengths(): void; + + /** + * Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance + */ + getUtoTmapping(u: number, distance: number): number; + + /** + * Returns a unit vector tangent at t. If the subclassed curve do not implement its tangent derivation, 2 points a small delta apart will be used to find its gradient which seems to give a reasonable approximation + * getTangent(t: number): T; + */ + getTangent(t: number): T; + + /** + * Returns tangent at equidistance point u on the curve + * getTangentAt(u: number): T; + */ + getTangentAt(u: number): T; + + static create(constructorFunc: Function, getPointFunc: Function): Function; + } + + export var CurveUtils: { + tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; + interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; + }; + + export interface BoundingBox { + minX: number; + minY: number; + minZ?: number; + maxX: number; + maxY: number; + maxZ?: number; + } + + export class CurvePath extends Curve { + constructor(); + + curves: Curve[]; + autoClose: boolean; + + add(curve: Curve): void; + checkConnection(): boolean; + closePath(): void; + getPoint(t: number): T; + getLength(): number; + getCurveLengths(): number[]; + createPointsGeometry(divisions: number): Geometry; + createSpacedPointsGeometry(divisions: number): Geometry; + createGeometry(points: T[]): Geometry; + } + + export enum PathActions { + MOVE_TO, + LINE_TO, + QUADRATIC_CURVE_TO, // Bezier quadratic curve + BEZIER_CURVE_TO, // Bezier cubic curve + CSPLINE_THRU, // Catmull-rom spline + ARC, // Circle + ELLIPSE, + } + + export interface PathAction { + action: PathActions; + args: any; + } + + /** + * a 2d path representation, comprising of points, lines, and cubes, similar to the html5 2d canvas api. It extends CurvePath. + */ + export class Path extends CurvePath { + constructor(points?: Vector2[]); + + actions: PathAction[]; + + fromPoints(vectors: Vector2[]): void; + moveTo(x: number, y: number): void; + lineTo(x: number, y: number): void; + quadraticCurveTo(aCPx: number, aCPy: number, aX: number, aY: number): void; + bezierCurveTo(aCP1x: number, aCP1y: number, aCP2x: number, aCP2y: number, aX: number, aY: number): void; + splineThru(pts: Vector2[]): void; + arc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; + ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; + absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; + getSpacedPoints(divisions?: number, closedPath?: boolean): Vector2[]; + getPoints(divisions?: number, closedPath?: boolean): Vector2[]; + toShapes(): Shape[]; + } + + /** + * Defines a 2d shape plane using paths. + */ + export class Shape extends Path { + constructor(points?: Vector2[]); + + holes: Path[]; + + extrude(options?: any): ExtrudeGeometry; + makeGeometry(options?: any): ShapeGeometry; + getPointsHoles(divisions: number): Vector2[][]; + extractAllPoints(divisions: number): { + shape: Vector2[]; + holes: Vector2[][]; + }; + extractPoints(divisions: number): Vector2[]; + + } + + // Extras / Curves ///////////////////////////////////////////////////////////////////// + export class ArcCurve extends EllipseCurve { + constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + } + + export class CatmullRomCurve3 extends Curve { + constructor(); + } + + export class ClosedSplineCurve3 extends Curve { + constructor(points?: Vector3[]); + + points: Vector3[]; + } + + export class CubicBezierCurve extends Curve { + constructor(v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2); + + v0: Vector2; + v1: Vector2; + v2: Vector2; + v3: Vector2; + } + export class CubicBezierCurve3 extends Curve { + constructor(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3); + + v0: Vector3; + v1: Vector3; + v2: Vector3; + v3: Vector3; + } + export class EllipseCurve extends Curve { + constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number); + + aX: number; + aY: number; + xRadius: number; + yRadius: number; + aStartAngle: number; + aEndAngle: number; + aClockwise: boolean; + aRotation: number; + } + export class LineCurve extends Curve { + constructor( v1: Vector2, v2: Vector2 ); + + v1: Vector2; + v2: Vector2; + + } + export class LineCurve3 extends Curve { + constructor( v1: Vector3, v2: Vector3 ); + + v1: Vector3; + v2: Vector3; + } + export class QuadraticBezierCurve extends Curve { + constructor( v0: Vector2, v1: Vector2, v2: Vector2 ); + + v0: Vector2; + v1: Vector2; + v2: Vector2; + } + export class QuadraticBezierCurve3 extends Curve { + constructor( v0: Vector3, v1: Vector3, v2: Vector3 ); + + v0: Vector3; + v1: Vector3; + v2: Vector3; + } + export class SplineCurve extends Curve { + constructor( points?: Vector2[] ); + + points:Vector2[]; + } + export class SplineCurve3 extends Curve { + constructor( points?: Vector3[] ); + + points:Vector3[]; + } + + // Extras / Geomerties ///////////////////////////////////////////////////////////////////// + /** + * BoxGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. + */ + export class BoxGeometry extends Geometry { + /** + * @param width — Width of the sides on the X axis. + * @param height — Height of the sides on the Y axis. + * @param depth — Depth of the sides on the Z axis. + * @param widthSegments — Number of segmented faces along the width of the sides. + * @param heightSegments — Number of segmented faces along the height of the sides. + * @param depthSegments — Number of segmented faces along the depth of the sides. + */ + constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); + + parameters: { + width: number; + height: number; + depth: number; + widthSegments: number; + heightSegments: number; + depthSegments: number; + }; + + clone(): BoxGeometry; + } + + export class CircleBufferGeometry extends Geometry { + constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + radius: number; + segments: number; + thetaStart: number; + thetaLength: number; + }; + + clone(): CircleBufferGeometry; + } + + export class CircleGeometry extends Geometry { + constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + radius: number; + segments: number; + thetaStart: number; + thetaLength: number; + }; + + clone(): CircleGeometry; + } + + // deprecated + export class CubeGeometry extends BoxGeometry { + } + + export class CylinderGeometry extends Geometry { + /** + * @param radiusTop — Radius of the cylinder at the top. + * @param radiusBottom — Radius of the cylinder at the bottom. + * @param height — Height of the cylinder. + * @param radiusSegments — Number of segmented faces around the circumference of the cylinder. + * @param heightSegments — Number of rows of faces along the height of the cylinder. + * @param openEnded - A Boolean indicating whether or not to cap the ends of the cylinder. + */ + constructor(radiusTop?: number, radiusBottom?: number, height?: number, radiusSegments?: number, heightSegments?: number, openEnded?: boolean, thetaStart?: number, thetaLength?: number); + + parameters: { + radiusTop: number; + radiusBottom: number; + height: number; + radialSegments: number; + heightSegments: number; + openEnded: boolean; + thetaStart: number; + thetaLength: number; + }; + + clone(): CylinderGeometry; + } + + export class DodecahedronGeometry extends Geometry { + constructor(radius: number, detail: number); + + parameters: { + radius: number; + detail: number; + }; + + clone(): DodecahedronGeometry; + } + + export class EdgesGeometry extends BufferGeometry { + constructor(geometry: BufferGeometry, thresholdAngle: number); + + clone(): EdgesGeometry; + } + + export class ExtrudeGeometry extends Geometry { + constructor(shape?: Shape, options?: any); + constructor(shapes?: Shape[], options?: any); + + static WorldUVGenerator: { + generateTopUV(geometry: Geometry, indexA: number, indexB: number, indexC: number): Vector2[]; + generateSideWallUV(geometry: Geometry, indexA: number, indexB: number, indexC: number, indexD: number): Vector2[]; + }; + + addShapeList(shapes: Shape[], options?: any): void; + addShape(shape: Shape, options?: any): void; + } + + export class IcosahedronGeometry extends PolyhedronGeometry { + constructor(radius: number, detail: number); + + clone(): IcosahedronGeometry; + } + + export class LatheGeometry extends Geometry { + constructor(points: Vector3[], segments?: number, phiStart?: number, phiLength?: number); + + parameters: { + points: Vector3[]; + segments: number; + phiStart: number; + phiLength: number; + }; + } + + export class OctahedronGeometry extends PolyhedronGeometry { + constructor(radius: number, detail: number); + + clone(): OctahedronGeometry; + } + + export class ParametricGeometry extends Geometry { + constructor(func: (u: number, v: number) => Vector3, slices: number, stacks: number); + + parameters: { + func: (u: number, v: number) => Vector3; + slices: number; + stacks: number; + }; + } + + export class PlaneBufferGeometry extends BufferGeometry { + constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); + + parameters: { + width: number; + height: number; + widthSegments: number; + heightSegments: number; + }; + + clone(): PlaneBufferGeometry; + } + + export class PlaneGeometry extends Geometry { + constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); + + parameters: { + width: number; + height: number; + widthSegments: number; + heightSegments: number; + }; + + clone(): PlaneGeometry; + } + + export class PolyhedronGeometry extends Geometry { + constructor(vertices: Vector3[], faces: Face3[], radius?: number, detail?: number); + + parameters: { + vertices: Vector3[]; + faces: Face3[]; + radius: number; + detail: number; + }; + + clone(): PolyhedronGeometry; + } + + export class RingGeometry extends Geometry { + constructor(innerRadius?: number, outerRadius?: number, thetaSegments?: number, phiSegments?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + innerRadius: number; + outerRadius: number; + thetaSegments: number; + phiSegments: number; + thetaStart: number; + thetaLength: number; + }; + + clone(): RingGeometry; + } + + export class ShapeGeometry extends Geometry { + constructor(shape: Shape, options?: any); + constructor(shapes: Shape[], options?: any); + + + addShapeList(shapes: Shape[], options: any): ShapeGeometry; + addShape(shape: Shape, options?: any): void; + } + + + export class SphereBufferGeometry extends BufferGeometry { + constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + radius: number; + widthSegments: number; + heightSegments: number; + phiStart: number; + phiLength: number; + thetaStart: number; + thetaLength: number; + }; + + clone(): SphereBufferGeometry; + } + + /** + * A class for generating sphere geometries + */ + export class SphereGeometry extends Geometry { + /** + * The geometry is created by sweeping and calculating vertexes around the Y axis (horizontal sweep) and the Z axis (vertical sweep). Thus, incomplete spheres (akin to 'sphere slices') can be created through the use of different values of phiStart, phiLength, thetaStart and thetaLength, in order to define the points in which we start (or end) calculating those vertices. + * + * @param radius — sphere radius. Default is 50. + * @param widthSegments — number of horizontal segments. Minimum value is 3, and the default is 8. + * @param heightSegments — number of vertical segments. Minimum value is 2, and the default is 6. + * @param phiStart — specify horizontal starting angle. Default is 0. + * @param phiLength — specify horizontal sweep angle size. Default is Math.PI * 2. + * @param thetaStart — specify vertical starting angle. Default is 0. + * @param thetaLength — specify vertical sweep angle size. Default is Math.PI. + */ + constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + radius: number; + widthSegments: number; + heightSegments: number; + phiStart: number; + phiLength: number; + thetaStart: number; + thetaLength: number; + }; + } + + export class TetrahedronGeometry extends PolyhedronGeometry { + constructor(radius?: number, detail?: number); + + clone(): TetrahedronGeometry; + } + + export class TorusGeometry extends Geometry { + constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, arc?: number); + + parameters: { + radius: number; + tube: number; + radialSegments: number; + tubularSegments: number; + arc: number; + }; + + clone(): TorusGeometry; + } + + export class TorusKnotGeometry extends Geometry { + constructor(radius?: number, tube?: number, radialSegments?: number, tubularSegments?: number, p?: number, q?: number, heightScale?: number); + + parameters: { + radius: number; + tube: number; + radialSegments: number; + tubularSegments: number; + p: number; + q: number; + heightScale: number; + }; + + clone(): TorusKnotGeometry; + } + + + export class TubeGeometry extends Geometry { + constructor(path: Path, segments?: number, radius?: number, radiusSegments?: number, closed?: boolean, taper?: (u: number) => number); + + parameters: { + path: Path; + segments: number; + radius: number; + radialSegments: number; + closed: boolean; + taper: (u: number) => number; // NoTaper or SinusoidalTaper; + }; + tangents: Vector3[]; + normals: Vector3[]; + binormals: Vector3[]; + + static NoTaper(u?: number): number; + static SinusoidalTaper(u: number): number; + static FrenetFrames(path: Path, segments: number, closed: boolean): void; + + clone(): TubeGeometry; + } + + export class WireframeGeometry extends BufferGeometry{ + constructor(geometry: Geometry | BufferGeometry); + } + + // Extras / Helpers ///////////////////////////////////////////////////////////////////// + + export class ArrowHelper extends Object3D { + constructor(dir: Vector3, origin?: Vector3, length?: number, hex?: number, headLength?: number, headWidth?: number); + + line: Line; + cone: Mesh; + + setDirection(dir: Vector3): void; + setLength(length: number, headLength?: number, headWidth?: number): void; + setColor(hex: number): void; + } + + export class AxisHelper extends LineSegments { + constructor(size?: number); + } + + export class BoundingBoxHelper extends Mesh { + constructor(object?: Object3D, hex?: number); + + object: Object3D; + box: Box3; + + update(): void; + } + + export class BoxHelper extends LineSegments { + constructor(object?: Object3D); + + update(object?: Object3D): void; + } + + export class CameraHelper extends LineSegments { + constructor(camera: Camera); + + camera: Camera; + pointMap: { [id: string]: number[]; }; + + update(): void; + } + + export class DirectionalLightHelper extends Object3D { + constructor(light: Light, size?: number); + + light: Light; + lightPlane: Line; + targetLine: Line; + + dispose(): void; + update(): void; + } + + export class EdgesHelper extends LineSegments { + constructor(object: Object3D, hex?: number, thresholdAngle?: number); + + } + + export class FaceNormalsHelper extends LineSegments { + constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); + + object: Object3D; + size: number; + + update(object?: Object3D): void; + } + + export class GridHelper extends LineSegments { + constructor(size: number, step: number); + + color1: Color; + color2: Color; + + setColors(colorCenterLine: number, colorGrid: number): void; + } + export class HemisphereLightHelper extends Object3D { + constructor(light: Light, sphereSize: number); + + light: Light; + colors: Color[]; + lightSphere: Mesh; + + dispose(): void; + update(): void; + } + + export class PointLightHelper extends Object3D { + constructor(light: Light, sphereSize: number); + + light: Light; + + dispose(): void; + update(): void; + } + + export class SkeletonHelper extends LineSegments { + constructor(bone: Object3D); + + bones: Bone[]; + root: Object3D; + + getBoneList(object: Object3D): Bone[]; + update(): void; + } + + export class SpotLightHelper extends Object3D { + constructor(light: Light, sphereSize: number, arrowLength: number); + + light: Light; + cone: Mesh; + + dispose(): void; + update(): void; + } + + export class VertexNormalsHelper extends LineSegments { + constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); + + object: Object3D; + size: number; + + update(object?: Object3D): void; + } + + export class WireframeHelper extends LineSegments { + constructor(object: Object3D, hex?: number); + + } + + // Extras / Objects ///////////////////////////////////////////////////////////////////// + + export class ImmediateRenderObject extends Object3D { + constructor(material: Material); + + material: Material; + render(renderCallback:Function): void; + } + + export interface MorphBlendMeshAnimation { + start: number; + end: number; + length: number; + fps: number; + duration: number; + lastFrame: number; + currentFrame: number; + active: boolean; + time: number; + direction: number; + weight: number; + directionBackwards: boolean; + mirroredLoop: boolean; + } + + export class MorphBlendMesh extends Mesh { + constructor(geometry: Geometry, material: Material); + + animationsMap: { [name: string]: MorphBlendMeshAnimation; }; + animationsList: MorphBlendMeshAnimation[]; + + createAnimation(name: string, start: number, end: number, fps: number): void; + autoCreateAnimations(fps: number): void; + setAnimationDirectionForward(name: string): void; + setAnimationDirectionBackward(name: string): void; + setAnimationFPS(name: string, fps: number): void; + setAnimationDuration(name: string, duration: number): void; + setAnimationWeight(name: string, weight: number): void; + setAnimationTime(name: string, time: number): void; + getAnimationTime(name: string): number; + getAnimationDuration(name: string): number; + playAnimation(name: string): void; + stopAnimation(name: string): void; + update(delta: number): void; + } +} + +declare module 'three' { + export = THREE; +} diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index a7bebb857..c4a836d61 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -1,204 +1,204 @@ -// Type definitions for WebRTC -// Project: http://dev.w3.org/2011/webrtc/ -// Definitions by: Ken Smith -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html -// version: W3C Editor's Draft 29 June 2015 - -/// - -interface ConstrainBooleanParameters { - exact?: boolean; - ideal?: boolean; -} - -interface NumberRange { - max?: number; - min?: number; -} - -interface ConstrainNumberRange extends NumberRange { - exact?: number; - ideal?: number; -} - -interface ConstrainStringParameters { - exact?: string | string[]; - ideal?: string | string[]; -} - -interface MediaStreamConstraints { - video?: boolean | MediaTrackConstraints; - audio?: boolean | MediaTrackConstraints; -} - -declare module W3C { - type LongRange = NumberRange; - type DoubleRange = NumberRange; - type ConstrainBoolean = boolean | ConstrainBooleanParameters; - type ConstrainNumber = number | ConstrainNumberRange; - type ConstrainLong = ConstrainNumber; - type ConstrainDouble = ConstrainNumber; - type ConstrainString = string | string[] | ConstrainStringParameters; -} - -interface MediaTrackConstraints extends MediaTrackConstraintSet { - advanced?: MediaTrackConstraintSet[]; -} - -interface MediaTrackConstraintSet { - width?: W3C.ConstrainLong; - height?: W3C.ConstrainLong; - aspectRatio?: W3C.ConstrainDouble; - frameRate?: W3C.ConstrainDouble; - facingMode?: W3C.ConstrainString; - volume?: W3C.ConstrainDouble; - sampleRate?: W3C.ConstrainLong; - sampleSize?: W3C.ConstrainLong; - echoCancellation?: W3C.ConstrainBoolean; - latency?: W3C.ConstrainDouble; - deviceId?: W3C.ConstrainString; - groupId?: W3C.ConstrainString; -} - -interface MediaTrackSupportedConstraints { - width?: boolean; - height?: boolean; - aspectRatio?: boolean; - frameRate?: boolean; - facingMode?: boolean; - volume?: boolean; - sampleRate?: boolean; - sampleSize?: boolean; - echoCancellation?: boolean; - latency?: boolean; - deviceId?: boolean; - groupId?: boolean; -} - -interface MediaStream extends EventTarget { - id: string; - active: boolean; - - onactive: EventListener; - oninactive: EventListener; - onaddtrack: (event: MediaStreamTrackEvent) => any; - onremovetrack: (event: MediaStreamTrackEvent) => any; - - clone(): MediaStream; - stop(): void; - - getAudioTracks(): MediaStreamTrack[]; - getVideoTracks(): MediaStreamTrack[]; - getTracks(): MediaStreamTrack[]; - - getTrackById(trackId: string): MediaStreamTrack; - - addTrack(track: MediaStreamTrack): void; - removeTrack(track: MediaStreamTrack): void; -} - -interface MediaStreamTrackEvent extends Event { - track: MediaStreamTrack; -} - -declare enum MediaStreamTrackState { - "live", - "ended" -} - -interface MediaStreamTrack extends EventTarget { - id: string; - kind: string; - label: string; - enabled: boolean; - muted: boolean; - remote: boolean; - readyState: MediaStreamTrackState; - - onmute: EventListener; - onunmute: EventListener; - onended: EventListener; - onoverconstrained: EventListener; - - clone(): MediaStreamTrack; - - stop(): void; - - getCapabilities(): MediaTrackCapabilities; - getConstraints(): MediaTrackConstraints; - getSettings(): MediaTrackSettings; - applyConstraints(constraints: MediaTrackConstraints): Promise; -} - -interface MediaTrackCapabilities { - width: number | W3C.LongRange; - height: number | W3C.LongRange; - aspectRatio: number | W3C.DoubleRange; - frameRate: number | W3C.DoubleRange; - facingMode: string; - volume: number | W3C.DoubleRange; - sampleRate: number | W3C.LongRange; - sampleSize: number | W3C.LongRange; - echoCancellation: boolean[]; - latency: number | W3C.DoubleRange; - deviceId: string; - groupId: string; -} - -interface MediaTrackSettings { - width: number; - height: number; - aspectRatio: number; - frameRate: number; - facingMode: string; - volume: number; - sampleRate: number; - sampleSize: number; - echoCancellation: boolean; - latency: number; - deviceId: string; - groupId: string; -} - -interface MediaStreamError { - name: string; - message: string; - constraintName: string; -} - -interface NavigatorGetUserMedia { - (constraints: MediaStreamConstraints, - successCallback: (stream: MediaStream) => void, - errorCallback: (error: MediaStreamError) => void): void; -} - -// to use with adapter.js, see: https://github.com/webrtc/adapter -declare var getUserMedia: NavigatorGetUserMedia; - -interface Navigator { - getUserMedia: NavigatorGetUserMedia; - - webkitGetUserMedia: NavigatorGetUserMedia; - - mozGetUserMedia: NavigatorGetUserMedia; - - msGetUserMedia: NavigatorGetUserMedia; - - mediaDevices: MediaDevices; -} - -interface MediaDevices { - getSupportedConstraints(): MediaTrackSupportedConstraints; - - getUserMedia(constraints: MediaStreamConstraints): Promise; - enumerateDevices(): Promise; -} - -interface MediaDeviceInfo { - label: string; - id: string; - kind: string; - facing: string; -} +// Type definitions for WebRTC +// Project: http://dev.w3.org/2011/webrtc/ +// Definitions by: Ken Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html +// version: W3C Editor's Draft 29 June 2015 + +/// + +interface ConstrainBooleanParameters { + exact?: boolean; + ideal?: boolean; +} + +interface NumberRange { + max?: number; + min?: number; +} + +interface ConstrainNumberRange extends NumberRange { + exact?: number; + ideal?: number; +} + +interface ConstrainStringParameters { + exact?: string | string[]; + ideal?: string | string[]; +} + +interface MediaStreamConstraints { + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; +} + +declare module W3C { + type LongRange = NumberRange; + type DoubleRange = NumberRange; + type ConstrainBoolean = boolean | ConstrainBooleanParameters; + type ConstrainNumber = number | ConstrainNumberRange; + type ConstrainLong = ConstrainNumber; + type ConstrainDouble = ConstrainNumber; + type ConstrainString = string | string[] | ConstrainStringParameters; +} + +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + +interface MediaTrackConstraintSet { + width?: W3C.ConstrainLong; + height?: W3C.ConstrainLong; + aspectRatio?: W3C.ConstrainDouble; + frameRate?: W3C.ConstrainDouble; + facingMode?: W3C.ConstrainString; + volume?: W3C.ConstrainDouble; + sampleRate?: W3C.ConstrainLong; + sampleSize?: W3C.ConstrainLong; + echoCancellation?: W3C.ConstrainBoolean; + latency?: W3C.ConstrainDouble; + deviceId?: W3C.ConstrainString; + groupId?: W3C.ConstrainString; +} + +interface MediaTrackSupportedConstraints { + width?: boolean; + height?: boolean; + aspectRatio?: boolean; + frameRate?: boolean; + facingMode?: boolean; + volume?: boolean; + sampleRate?: boolean; + sampleSize?: boolean; + echoCancellation?: boolean; + latency?: boolean; + deviceId?: boolean; + groupId?: boolean; +} + +interface MediaStream extends EventTarget { + id: string; + active: boolean; + + onactive: EventListener; + oninactive: EventListener; + onaddtrack: (event: MediaStreamTrackEvent) => any; + onremovetrack: (event: MediaStreamTrackEvent) => any; + + clone(): MediaStream; + stop(): void; + + getAudioTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + getTracks(): MediaStreamTrack[]; + + getTrackById(trackId: string): MediaStreamTrack; + + addTrack(track: MediaStreamTrack): void; + removeTrack(track: MediaStreamTrack): void; +} + +interface MediaStreamTrackEvent extends Event { + track: MediaStreamTrack; +} + +declare enum MediaStreamTrackState { + "live", + "ended" +} + +interface MediaStreamTrack extends EventTarget { + id: string; + kind: string; + label: string; + enabled: boolean; + muted: boolean; + remote: boolean; + readyState: MediaStreamTrackState; + + onmute: EventListener; + onunmute: EventListener; + onended: EventListener; + onoverconstrained: EventListener; + + clone(): MediaStreamTrack; + + stop(): void; + + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + applyConstraints(constraints: MediaTrackConstraints): Promise; +} + +interface MediaTrackCapabilities { + width: number | W3C.LongRange; + height: number | W3C.LongRange; + aspectRatio: number | W3C.DoubleRange; + frameRate: number | W3C.DoubleRange; + facingMode: string; + volume: number | W3C.DoubleRange; + sampleRate: number | W3C.LongRange; + sampleSize: number | W3C.LongRange; + echoCancellation: boolean[]; + latency: number | W3C.DoubleRange; + deviceId: string; + groupId: string; +} + +interface MediaTrackSettings { + width: number; + height: number; + aspectRatio: number; + frameRate: number; + facingMode: string; + volume: number; + sampleRate: number; + sampleSize: number; + echoCancellation: boolean; + latency: number; + deviceId: string; + groupId: string; +} + +interface MediaStreamError { + name: string; + message: string; + constraintName: string; +} + +interface NavigatorGetUserMedia { + (constraints: MediaStreamConstraints, + successCallback: (stream: MediaStream) => void, + errorCallback: (error: MediaStreamError) => void): void; +} + +// to use with adapter.js, see: https://github.com/webrtc/adapter +declare var getUserMedia: NavigatorGetUserMedia; + +interface Navigator { + getUserMedia: NavigatorGetUserMedia; + + webkitGetUserMedia: NavigatorGetUserMedia; + + mozGetUserMedia: NavigatorGetUserMedia; + + msGetUserMedia: NavigatorGetUserMedia; + + mediaDevices: MediaDevices; +} + +interface MediaDevices { + getSupportedConstraints(): MediaTrackSupportedConstraints; + + getUserMedia(constraints: MediaStreamConstraints): Promise; + enumerateDevices(): Promise; +} + +interface MediaDeviceInfo { + label: string; + id: string; + kind: string; + facing: string; +} diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index b85c61806..1ed79bf2c 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -1,90 +1,90 @@ -/// -/// - -var config: RTCConfiguration = - { iceServers: [{ urls: "stun.l.google.com:19302" }] }; -var constraints: RTCMediaConstraints = - { mandatory: { offerToReceiveAudio: true, offerToReceiveVideo: true } }; - -var peerConnection: RTCPeerConnection = - new RTCPeerConnection(config, constraints); - -navigator.getUserMedia({ audio: true, video: true }, - stream => { - peerConnection.addStream(stream); - }, - error => { - console.log('Error message: ' + error.message); - console.log('Error name: ' + error.name); - }); - -peerConnection.onaddstream = ev => console.log(ev.type); -peerConnection.ondatachannel = ev => console.log(ev.type); -peerConnection.oniceconnectionstatechange = ev => console.log(ev.type); -peerConnection.onnegotiationneeded = ev => console.log(ev.type); -peerConnection.onopen = ev => console.log(ev.type); -peerConnection.onicecandidate = ev => console.log(ev.type); -peerConnection.onremovestream = ev => console.log(ev.type); -peerConnection.onstatechange = ev => console.log(ev.type); - -peerConnection.createOffer( - offer => { - peerConnection.setLocalDescription(offer, - () => console.log("set local description"), - error => console.log("Error setting local description: " + error)); - }, - error => console.log("Error creating offer: " + error)); - -var type: string = RTCSdpType[RTCSdpType.offer]; -var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; -var sessionDescription = new RTCSessionDescription(offer); - -peerConnection.setRemoteDescription(sessionDescription, () => { - peerConnection.createAnswer( - answer => { - peerConnection.setLocalDescription(answer, - () => console.log('Set local description'), - error => console.log( - "Error setting local description from created answer: " + error + - "; answer.sdp=" + answer.sdp)); - }, - error => console.log("Error creating answer: " + error)); -}, -error => console.log('Error setting remote description: ' + error + - "; offer.sdp=" + offer.sdp)); - -var webkitSessionDescription = new webkitRTCSessionDescription(offer); - -peerConnection.setRemoteDescription(webkitSessionDescription, () => { - peerConnection.createAnswer( - answer => { - peerConnection.setLocalDescription(answer, - () => console.log('Set local description'), - error => console.log( - "Error setting local description from created answer: " + error + - "; answer.sdp=" + answer.sdp)); - }, - error => console.log("Error creating answer: " + error)); -}, -error => console.log('Error setting remote description: ' + error + - "; offer.sdp=" + offer.sdp)); - -var mozSessionDescription = new mozRTCSessionDescription(offer); - -peerConnection.setRemoteDescription(mozSessionDescription, () => { - peerConnection.createAnswer( - answer => { - peerConnection.setLocalDescription(answer, - () => console.log('Set local description'), - error => console.log( - "Error setting local description from created answer: " + error + - "; answer.sdp=" + answer.sdp)); - }, - error => console.log("Error creating answer: " + error)); -}, -error => console.log('Error setting remote description: ' + error + - "; offer.sdp=" + offer.sdp)); - -var wkPeerConnection: webkitRTCPeerConnection = - new webkitRTCPeerConnection(config, constraints); - +/// +/// + +var config: RTCConfiguration = + { iceServers: [{ urls: "stun.l.google.com:19302" }] }; +var constraints: RTCMediaConstraints = + { mandatory: { offerToReceiveAudio: true, offerToReceiveVideo: true } }; + +var peerConnection: RTCPeerConnection = + new RTCPeerConnection(config, constraints); + +navigator.getUserMedia({ audio: true, video: true }, + stream => { + peerConnection.addStream(stream); + }, + error => { + console.log('Error message: ' + error.message); + console.log('Error name: ' + error.name); + }); + +peerConnection.onaddstream = ev => console.log(ev.type); +peerConnection.ondatachannel = ev => console.log(ev.type); +peerConnection.oniceconnectionstatechange = ev => console.log(ev.type); +peerConnection.onnegotiationneeded = ev => console.log(ev.type); +peerConnection.onopen = ev => console.log(ev.type); +peerConnection.onicecandidate = ev => console.log(ev.type); +peerConnection.onremovestream = ev => console.log(ev.type); +peerConnection.onstatechange = ev => console.log(ev.type); + +peerConnection.createOffer( + offer => { + peerConnection.setLocalDescription(offer, + () => console.log("set local description"), + error => console.log("Error setting local description: " + error)); + }, + error => console.log("Error creating offer: " + error)); + +var type: string = RTCSdpType[RTCSdpType.offer]; +var offer: RTCSessionDescriptionInit = { type: type, sdp: "some sdp" }; +var sessionDescription = new RTCSessionDescription(offer); + +peerConnection.setRemoteDescription(sessionDescription, () => { + peerConnection.createAnswer( + answer => { + peerConnection.setLocalDescription(answer, + () => console.log('Set local description'), + error => console.log( + "Error setting local description from created answer: " + error + + "; answer.sdp=" + answer.sdp)); + }, + error => console.log("Error creating answer: " + error)); +}, +error => console.log('Error setting remote description: ' + error + + "; offer.sdp=" + offer.sdp)); + +var webkitSessionDescription = new webkitRTCSessionDescription(offer); + +peerConnection.setRemoteDescription(webkitSessionDescription, () => { + peerConnection.createAnswer( + answer => { + peerConnection.setLocalDescription(answer, + () => console.log('Set local description'), + error => console.log( + "Error setting local description from created answer: " + error + + "; answer.sdp=" + answer.sdp)); + }, + error => console.log("Error creating answer: " + error)); +}, +error => console.log('Error setting remote description: ' + error + + "; offer.sdp=" + offer.sdp)); + +var mozSessionDescription = new mozRTCSessionDescription(offer); + +peerConnection.setRemoteDescription(mozSessionDescription, () => { + peerConnection.createAnswer( + answer => { + peerConnection.setLocalDescription(answer, + () => console.log('Set local description'), + error => console.log( + "Error setting local description from created answer: " + error + + "; answer.sdp=" + answer.sdp)); + }, + error => console.log("Error creating answer: " + error)); +}, +error => console.log('Error setting remote description: ' + error + + "; offer.sdp=" + offer.sdp)); + +var wkPeerConnection: webkitRTCPeerConnection = + new webkitRTCPeerConnection(config, constraints); + diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index 661b9685b..0594f84c3 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -1,363 +1,363 @@ -// Type definitions for WebRTC -// Project: http://dev.w3.org/2011/webrtc/ -// Definitions by: Ken Smith -// Definitions: https://github.com/borisyankov/DefinitelyTyped -// -// Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html -// -// For example code see: -// https://code.google.com/p/webrtc/source/browse/stable/samples/js/apprtc/js/main.js -// -// For a generic implementation see that deals with browser differences, see: -// https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js - -/// - -// TODO(1): Get Typescript to have string-enum types as WebRtc is full of string -// enums. -// https://typescript.codeplex.com/discussions/549207 - -// TODO(2): get Typescript to have union types as WebRtc uses them. -// https://typescript.codeplex.com/workitem/1364 - -interface RTCConfiguration { - iceServers: RTCIceServer[]; -} -declare var RTCConfiguration: { - prototype: RTCConfiguration; - new (): RTCConfiguration; -}; - -interface RTCIceServer { - urls: string; - credential?: string; -} -declare var RTCIceServer: { - prototype: RTCIceServer; - new (): RTCIceServer; -}; - -// moz (Firefox) specific prefixes. -interface mozRTCPeerConnection extends RTCPeerConnection { -} -declare var mozRTCPeerConnection: { - prototype: mozRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, - constraints?:RTCMediaConstraints): mozRTCPeerConnection; -}; -// webkit (Chrome) specific prefixes. -interface webkitRTCPeerConnection extends RTCPeerConnection { -} -declare var webkitRTCPeerConnection: { - prototype: webkitRTCPeerConnection; - new (settings: RTCPeerConnectionConfig, - constraints?:RTCMediaConstraints): webkitRTCPeerConnection; -}; - -// For Chrome, look at the code here: -// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 -interface RTCOptionalMediaConstraint { - // When true, will use DTLS/SCTP data channels - DtlsSrtpKeyAgreement?: boolean; - // When true will use Rtp-based data channels (depreicated) - RtpDataChannels?: boolean; -} - -// ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. -// http://www.w3.org/TR/2013/WD-webrtc-20130910/ -interface RTCMediaConstraints { - mandatory?: RTCMediaOfferConstraints; - optional?: RTCOptionalMediaConstraint[] -} - -interface RTCMediaOfferConstraints { - offerToReceiveAudio: boolean; - offerToReceiveVideo: boolean; -} - -interface RTCSessionDescriptionInit { - type: string; // RTCSdpType; See TODO(1) - sdp: string; -} - -interface RTCSessionDescription { - type?: string; // RTCSdpType; See TODO(1) - sdp?: string; -} -declare var RTCSessionDescription: { - prototype: RTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; - // TODO: Add serializer. - // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) -}; - -interface webkitRTCSessionDescription extends RTCSessionDescription{ - type?: string; - sdp?: string; -} -declare var webkitRTCSessionDescription: { - prototype: webkitRTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): webkitRTCSessionDescription; -}; - -interface mozRTCSessionDescription extends RTCSessionDescription{ - type?: string; - sdp?: string; -} -declare var mozRTCSessionDescription: { - prototype: mozRTCSessionDescription; - new (descriptionInitDict?: RTCSessionDescriptionInit): mozRTCSessionDescription; -}; - - - -interface RTCDataChannelInit { - ordered ?: boolean; // messages must be sent in-order. - maxPacketLifeTime ?: number; // unsigned short - maxRetransmits ?: number; // unsigned short - protocol ?: string; // default = '' - negotiated ?: boolean; // default = false; - id ?: number; // unsigned short -} - -// TODO(1) -declare enum RTCSdpType { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype - 'offer', - 'pranswer', - 'answer' -} - -interface RTCMessageEvent { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message - // At present, this can be an: ArrayBuffer, a string, or a Blob. - // See TODO(2) - data: any; -} - -// TODO(1) -declare enum RTCDataChannelState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState - 'connecting', - 'open', - 'closing', - 'closed' -} - -interface RTCDataChannel extends EventTarget { - label: string; - reliable: boolean; - readyState: string; // RTCDataChannelState; see TODO(1) - bufferedAmount: number; - binaryType: string; - - onopen: (event: Event) => void; - onerror: (event: Event) => void; - onclose: (event: Event) => void; - onmessage: (event: RTCMessageEvent) => void; - - close(): void; - - send(data: string): void ; - send(data: ArrayBuffer): void; - send(data: ArrayBufferView): void; - send(data: Blob): void; -} -declare var RTCDataChannel: { - prototype: RTCDataChannel; - new (): RTCDataChannel; -}; - -interface RTCDataChannelEvent extends Event { - channel: RTCDataChannel; -} -declare var RTCDataChannelEvent: { - prototype: RTCDataChannelEvent; - new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; -}; - -interface RTCIceCandidateEvent extends Event { - candidate: RTCIceCandidate; -} - -interface RTCMediaStreamEvent extends Event { - stream: MediaStream; -} - -interface EventInit { -} - -interface RTCDataChannelEventInit extends EventInit { - channel: RTCDataChannel; -} - -interface RTCVoidCallback { - (): void; -} -interface RTCSessionDescriptionCallback { - (sdp: RTCSessionDescription): void; -} -interface RTCPeerConnectionErrorCallback { - (errorInformation: DOMError): void; -} - -// TODO(1) -declare enum RTCIceGatheringState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum - 'new', - 'gathering', - 'complete' -} - -// TODO(1) -declare enum RTCIceConnectionState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState - 'new', - 'checking', - 'connected', - 'completed', - 'failed', - 'disconnected', - 'closed' -} - -// TODO(1) -declare enum RTCSignalingState { - // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState - 'stable', - 'have-local-offer', - 'have-remote-offer', - 'have-local-pranswer', - 'have-remote-pranswer', - 'closed' -} - -// This is based on the current implementation of WebRtc in Chrome; the spec is -// a little unclear on this. -// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCStatsReport -interface RTCStatsReport { - stat(id: string): string; -} - -interface RTCStatsCallback { - (report: RTCStatsReport): void; -} - -interface RTCPeerConnection { - createOffer(successCallback: RTCSessionDescriptionCallback, - failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: RTCMediaConstraints): void; - createAnswer(successCallback: RTCSessionDescriptionCallback, - failureCallback?: RTCPeerConnectionErrorCallback, - constraints?: RTCMediaConstraints): void; - setLocalDescription(description: RTCSessionDescription, - successCallback?: RTCVoidCallback, - failureCallback?: RTCPeerConnectionErrorCallback): void; - localDescription: RTCSessionDescription; - setRemoteDescription(description: RTCSessionDescription, - successCallback?: RTCVoidCallback, - failureCallback?: RTCPeerConnectionErrorCallback): void; - remoteDescription: RTCSessionDescription; - signalingState: string; // RTCSignalingState; see TODO(1) - updateIce(configuration?: RTCConfiguration, - constraints?: RTCMediaConstraints): void; - addIceCandidate(candidate:RTCIceCandidate, - successCallback:() => void, - failureCallback:RTCPeerConnectionErrorCallback): void; - iceGatheringState: string; // RTCIceGatheringState; see TODO(1) - iceConnectionState: string; // RTCIceConnectionState; see TODO(1) - getLocalStreams(): MediaStream[]; - getRemoteStreams(): MediaStream[]; - createDataChannel(label?: string, - dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: Event) => void; - addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; - removeStream(stream: MediaStream): void; - close(): void; - onnegotiationneeded: (event: Event) => void; - onconnecting: (event: Event) => void; - onopen: (event: Event) => void; - onaddstream: (event: RTCMediaStreamEvent) => void; - onremovestream: (event: RTCMediaStreamEvent) => void; - onstatechange: (event: Event) => void; - oniceconnectionstatechange: (event: Event) => void; - onicecandidate: (event: RTCIceCandidateEvent) => void; - onidentityresult: (event: Event) => void; - onsignalingstatechange: (event: Event) => void; - getStats: (successCallback: RTCStatsCallback, - failureCallback: RTCPeerConnectionErrorCallback) => void; -} -declare var RTCPeerConnection: { - prototype: RTCPeerConnection; - new (configuration: RTCConfiguration, - constraints?: RTCMediaConstraints): RTCPeerConnection; -}; - -interface RTCIceCandidate { - candidate?: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var RTCIceCandidate: { - prototype: RTCIceCandidate; - new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; -}; - -interface webkitRTCIceCandidate extends RTCIceCandidate { - candidate?: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var webkitRTCIceCandidate: { - prototype: webkitRTCIceCandidate; - new (candidateInitDict?: webkitRTCIceCandidate): webkitRTCIceCandidate; -}; - -interface mozRTCIceCandidate extends RTCIceCandidate { - candidate?: string; - sdpMid?: string; - sdpMLineIndex?: number; -} -declare var mozRTCIceCandidate: { - prototype: mozRTCIceCandidate; - new (candidateInitDict?: mozRTCIceCandidate): mozRTCIceCandidate; -}; - -interface RTCIceCandidateInit { - candidate: string; - sdpMid: string; - sdpMLineIndex: number; -} -declare var RTCIceCandidateInit:{ - prototype: RTCIceCandidateInit; - new (): RTCIceCandidateInit; -}; - -interface PeerConnectionIceEvent { - peer: RTCPeerConnection; - candidate: RTCIceCandidate; -} -declare var PeerConnectionIceEvent: { - prototype: PeerConnectionIceEvent; - new (): PeerConnectionIceEvent; -}; - -interface RTCPeerConnectionConfig { - iceServers: RTCIceServer[]; -} -declare var RTCPeerConnectionConfig: { - prototype: RTCPeerConnectionConfig; - new (): RTCPeerConnectionConfig; -}; - -interface Window{ - RTCPeerConnection: RTCPeerConnection; - webkitRTCPeerConnection: webkitRTCPeerConnection; - mozRTCPeerConnection: mozRTCPeerConnection; - RTCSessionDescription: RTCSessionDescription; - webkitRTCSessionDescription: webkitRTCSessionDescription; - mozRTCSessionDescription: mozRTCSessionDescription; - RTCIceCandidate: RTCIceCandidate; - webkitRTCIceCandidate: webkitRTCIceCandidate; - mozRTCIceCandidate: mozRTCIceCandidate; -} +// Type definitions for WebRTC +// Project: http://dev.w3.org/2011/webrtc/ +// Definitions by: Ken Smith +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// +// Definitions taken from http://dev.w3.org/2011/webrtc/editor/webrtc.html +// +// For example code see: +// https://code.google.com/p/webrtc/source/browse/stable/samples/js/apprtc/js/main.js +// +// For a generic implementation see that deals with browser differences, see: +// https://code.google.com/p/webrtc/source/browse/stable/samples/js/base/adapter.js + +/// + +// TODO(1): Get Typescript to have string-enum types as WebRtc is full of string +// enums. +// https://typescript.codeplex.com/discussions/549207 + +// TODO(2): get Typescript to have union types as WebRtc uses them. +// https://typescript.codeplex.com/workitem/1364 + +interface RTCConfiguration { + iceServers: RTCIceServer[]; +} +declare var RTCConfiguration: { + prototype: RTCConfiguration; + new (): RTCConfiguration; +}; + +interface RTCIceServer { + urls: string; + credential?: string; +} +declare var RTCIceServer: { + prototype: RTCIceServer; + new (): RTCIceServer; +}; + +// moz (Firefox) specific prefixes. +interface mozRTCPeerConnection extends RTCPeerConnection { +} +declare var mozRTCPeerConnection: { + prototype: mozRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:RTCMediaConstraints): mozRTCPeerConnection; +}; +// webkit (Chrome) specific prefixes. +interface webkitRTCPeerConnection extends RTCPeerConnection { +} +declare var webkitRTCPeerConnection: { + prototype: webkitRTCPeerConnection; + new (settings: RTCPeerConnectionConfig, + constraints?:RTCMediaConstraints): webkitRTCPeerConnection; +}; + +// For Chrome, look at the code here: +// https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 +interface RTCOptionalMediaConstraint { + // When true, will use DTLS/SCTP data channels + DtlsSrtpKeyAgreement?: boolean; + // When true will use Rtp-based data channels (depreicated) + RtpDataChannels?: boolean; +} + +// ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. +// http://www.w3.org/TR/2013/WD-webrtc-20130910/ +interface RTCMediaConstraints { + mandatory?: RTCMediaOfferConstraints; + optional?: RTCOptionalMediaConstraint[] +} + +interface RTCMediaOfferConstraints { + offerToReceiveAudio: boolean; + offerToReceiveVideo: boolean; +} + +interface RTCSessionDescriptionInit { + type: string; // RTCSdpType; See TODO(1) + sdp: string; +} + +interface RTCSessionDescription { + type?: string; // RTCSdpType; See TODO(1) + sdp?: string; +} +declare var RTCSessionDescription: { + prototype: RTCSessionDescription; + new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; + // TODO: Add serializer. + // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) +}; + +interface webkitRTCSessionDescription extends RTCSessionDescription{ + type?: string; + sdp?: string; +} +declare var webkitRTCSessionDescription: { + prototype: webkitRTCSessionDescription; + new (descriptionInitDict?: RTCSessionDescriptionInit): webkitRTCSessionDescription; +}; + +interface mozRTCSessionDescription extends RTCSessionDescription{ + type?: string; + sdp?: string; +} +declare var mozRTCSessionDescription: { + prototype: mozRTCSessionDescription; + new (descriptionInitDict?: RTCSessionDescriptionInit): mozRTCSessionDescription; +}; + + + +interface RTCDataChannelInit { + ordered ?: boolean; // messages must be sent in-order. + maxPacketLifeTime ?: number; // unsigned short + maxRetransmits ?: number; // unsigned short + protocol ?: string; // default = '' + negotiated ?: boolean; // default = false; + id ?: number; // unsigned short +} + +// TODO(1) +declare enum RTCSdpType { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype + 'offer', + 'pranswer', + 'answer' +} + +interface RTCMessageEvent { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message + // At present, this can be an: ArrayBuffer, a string, or a Blob. + // See TODO(2) + data: any; +} + +// TODO(1) +declare enum RTCDataChannelState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState + 'connecting', + 'open', + 'closing', + 'closed' +} + +interface RTCDataChannel extends EventTarget { + label: string; + reliable: boolean; + readyState: string; // RTCDataChannelState; see TODO(1) + bufferedAmount: number; + binaryType: string; + + onopen: (event: Event) => void; + onerror: (event: Event) => void; + onclose: (event: Event) => void; + onmessage: (event: RTCMessageEvent) => void; + + close(): void; + + send(data: string): void ; + send(data: ArrayBuffer): void; + send(data: ArrayBufferView): void; + send(data: Blob): void; +} +declare var RTCDataChannel: { + prototype: RTCDataChannel; + new (): RTCDataChannel; +}; + +interface RTCDataChannelEvent extends Event { + channel: RTCDataChannel; +} +declare var RTCDataChannelEvent: { + prototype: RTCDataChannelEvent; + new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; +}; + +interface RTCIceCandidateEvent extends Event { + candidate: RTCIceCandidate; +} + +interface RTCMediaStreamEvent extends Event { + stream: MediaStream; +} + +interface EventInit { +} + +interface RTCDataChannelEventInit extends EventInit { + channel: RTCDataChannel; +} + +interface RTCVoidCallback { + (): void; +} +interface RTCSessionDescriptionCallback { + (sdp: RTCSessionDescription): void; +} +interface RTCPeerConnectionErrorCallback { + (errorInformation: DOMError): void; +} + +// TODO(1) +declare enum RTCIceGatheringState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum + 'new', + 'gathering', + 'complete' +} + +// TODO(1) +declare enum RTCIceConnectionState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState + 'new', + 'checking', + 'connected', + 'completed', + 'failed', + 'disconnected', + 'closed' +} + +// TODO(1) +declare enum RTCSignalingState { + // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState + 'stable', + 'have-local-offer', + 'have-remote-offer', + 'have-local-pranswer', + 'have-remote-pranswer', + 'closed' +} + +// This is based on the current implementation of WebRtc in Chrome; the spec is +// a little unclear on this. +// http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCStatsReport +interface RTCStatsReport { + stat(id: string): string; +} + +interface RTCStatsCallback { + (report: RTCStatsReport): void; +} + +interface RTCPeerConnection { + createOffer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: RTCMediaConstraints): void; + createAnswer(successCallback: RTCSessionDescriptionCallback, + failureCallback?: RTCPeerConnectionErrorCallback, + constraints?: RTCMediaConstraints): void; + setLocalDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; + localDescription: RTCSessionDescription; + setRemoteDescription(description: RTCSessionDescription, + successCallback?: RTCVoidCallback, + failureCallback?: RTCPeerConnectionErrorCallback): void; + remoteDescription: RTCSessionDescription; + signalingState: string; // RTCSignalingState; see TODO(1) + updateIce(configuration?: RTCConfiguration, + constraints?: RTCMediaConstraints): void; + addIceCandidate(candidate:RTCIceCandidate, + successCallback:() => void, + failureCallback:RTCPeerConnectionErrorCallback): void; + iceGatheringState: string; // RTCIceGatheringState; see TODO(1) + iceConnectionState: string; // RTCIceConnectionState; see TODO(1) + getLocalStreams(): MediaStream[]; + getRemoteStreams(): MediaStream[]; + createDataChannel(label?: string, + dataChannelDict?: RTCDataChannelInit): RTCDataChannel; + ondatachannel: (event: Event) => void; + addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; + removeStream(stream: MediaStream): void; + close(): void; + onnegotiationneeded: (event: Event) => void; + onconnecting: (event: Event) => void; + onopen: (event: Event) => void; + onaddstream: (event: RTCMediaStreamEvent) => void; + onremovestream: (event: RTCMediaStreamEvent) => void; + onstatechange: (event: Event) => void; + oniceconnectionstatechange: (event: Event) => void; + onicecandidate: (event: RTCIceCandidateEvent) => void; + onidentityresult: (event: Event) => void; + onsignalingstatechange: (event: Event) => void; + getStats: (successCallback: RTCStatsCallback, + failureCallback: RTCPeerConnectionErrorCallback) => void; +} +declare var RTCPeerConnection: { + prototype: RTCPeerConnection; + new (configuration: RTCConfiguration, + constraints?: RTCMediaConstraints): RTCPeerConnection; +}; + +interface RTCIceCandidate { + candidate?: string; + sdpMid?: string; + sdpMLineIndex?: number; +} +declare var RTCIceCandidate: { + prototype: RTCIceCandidate; + new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; +}; + +interface webkitRTCIceCandidate extends RTCIceCandidate { + candidate?: string; + sdpMid?: string; + sdpMLineIndex?: number; +} +declare var webkitRTCIceCandidate: { + prototype: webkitRTCIceCandidate; + new (candidateInitDict?: webkitRTCIceCandidate): webkitRTCIceCandidate; +}; + +interface mozRTCIceCandidate extends RTCIceCandidate { + candidate?: string; + sdpMid?: string; + sdpMLineIndex?: number; +} +declare var mozRTCIceCandidate: { + prototype: mozRTCIceCandidate; + new (candidateInitDict?: mozRTCIceCandidate): mozRTCIceCandidate; +}; + +interface RTCIceCandidateInit { + candidate: string; + sdpMid: string; + sdpMLineIndex: number; +} +declare var RTCIceCandidateInit:{ + prototype: RTCIceCandidateInit; + new (): RTCIceCandidateInit; +}; + +interface PeerConnectionIceEvent { + peer: RTCPeerConnection; + candidate: RTCIceCandidate; +} +declare var PeerConnectionIceEvent: { + prototype: PeerConnectionIceEvent; + new (): PeerConnectionIceEvent; +}; + +interface RTCPeerConnectionConfig { + iceServers: RTCIceServer[]; +} +declare var RTCPeerConnectionConfig: { + prototype: RTCPeerConnectionConfig; + new (): RTCPeerConnectionConfig; +}; + +interface Window{ + RTCPeerConnection: RTCPeerConnection; + webkitRTCPeerConnection: webkitRTCPeerConnection; + mozRTCPeerConnection: mozRTCPeerConnection; + RTCSessionDescription: RTCSessionDescription; + webkitRTCSessionDescription: webkitRTCSessionDescription; + mozRTCSessionDescription: mozRTCSessionDescription; + RTCIceCandidate: RTCIceCandidate; + webkitRTCIceCandidate: webkitRTCIceCandidate; + mozRTCIceCandidate: mozRTCIceCandidate; +}