language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Source { constructor( body, name = "GraphQL request", locationOffset = { line: 1, column: 1, } ) { typeof body === "string" || devAssert(false, `Body must be a string. Received: ${inspect(body)}.`); this.body = body; this.name = name; this.locationOffset = locationOffset; this.locationOffset.line > 0 || devAssert( false, "line in locationOffset is 1-indexed and must be positive." ); this.locationOffset.column > 0 || devAssert( false, "column in locationOffset is 1-indexed and must be positive." ); } get [Symbol.toStringTag]() { return "Source"; } }
JavaScript
class Lexer { /** * The previously focused non-ignored token. */ /** * The currently focused non-ignored token. */ /** * The (1-indexed) line containing the current token. */ /** * The character offset at which the current line begins. */ constructor(source) { const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0); this.source = source; this.lastToken = startOfFileToken; this.token = startOfFileToken; this.line = 1; this.lineStart = 0; } get [Symbol.toStringTag]() { return "Lexer"; } /** * Advances the token stream to the next non-ignored token. */ advance() { this.lastToken = this.token; const token = (this.token = this.lookahead()); return token; } /** * Looks ahead and returns the next non-ignored token, but does not change * the state of Lexer. */ lookahead() { let token = this.token; if (token.kind !== TokenKind.EOF) { do { if (token.next) { token = token.next; } else { // Read the next token and form a link in the token linked-list. const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. nextToken.prev = token; token = nextToken; } } while (token.kind === TokenKind.COMMENT); } return token; } }
JavaScript
class Parser { constructor(source, options) { const sourceObj = isSource(source) ? source : new Source(source); this._lexer = new Lexer(sourceObj); this._options = options; } /** * Converts a name lex token into a name parse node. */ parseName() { const token = this.expectToken(TokenKind.NAME); return this.node(token, { kind: Kind.NAME, value: token.value, }); } // Implements the parsing rules in the Document section. /** * Document : Definition+ */ parseDocument() { return this.node(this._lexer.token, { kind: Kind.DOCUMENT, definitions: this.many( TokenKind.SOF, this.parseDefinition, TokenKind.EOF ), }); } /** * Definition : * - ExecutableDefinition * - TypeSystemDefinition * - TypeSystemExtension * * ExecutableDefinition : * - OperationDefinition * - FragmentDefinition * * TypeSystemDefinition : * - SchemaDefinition * - TypeDefinition * - DirectiveDefinition * * TypeDefinition : * - ScalarTypeDefinition * - ObjectTypeDefinition * - InterfaceTypeDefinition * - UnionTypeDefinition * - EnumTypeDefinition * - InputObjectTypeDefinition */ parseDefinition() { if (this.peek(TokenKind.BRACE_L)) { return this.parseOperationDefinition(); } // Many definitions begin with a description and require a lookahead. const hasDescription = this.peekDescription(); const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token; if (keywordToken.kind === TokenKind.NAME) { switch (keywordToken.value) { case "schema": return this.parseSchemaDefinition(); case "scalar": return this.parseScalarTypeDefinition(); case "type": return this.parseObjectTypeDefinition(); case "interface": return this.parseInterfaceTypeDefinition(); case "union": return this.parseUnionTypeDefinition(); case "enum": return this.parseEnumTypeDefinition(); case "input": return this.parseInputObjectTypeDefinition(); case "directive": return this.parseDirectiveDefinition(); } if (hasDescription) { throw syntaxError( this._lexer.source, this._lexer.token.start, "Unexpected description, descriptions are supported only on type definitions." ); } switch (keywordToken.value) { case "query": case "mutation": case "subscription": return this.parseOperationDefinition(); case "fragment": return this.parseFragmentDefinition(); case "extend": return this.parseTypeSystemExtension(); } } throw this.unexpected(keywordToken); } // Implements the parsing rules in the Operations section. /** * OperationDefinition : * - SelectionSet * - OperationType Name? VariableDefinitions? Directives? SelectionSet */ parseOperationDefinition() { const start = this._lexer.token; if (this.peek(TokenKind.BRACE_L)) { return this.node(start, { kind: Kind.OPERATION_DEFINITION, operation: OperationTypeNode.QUERY, name: undefined, variableDefinitions: [], directives: [], selectionSet: this.parseSelectionSet(), }); } const operation = this.parseOperationType(); let name; if (this.peek(TokenKind.NAME)) { name = this.parseName(); } return this.node(start, { kind: Kind.OPERATION_DEFINITION, operation, name, variableDefinitions: this.parseVariableDefinitions(), directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), }); } /** * OperationType : one of query mutation subscription */ parseOperationType() { const operationToken = this.expectToken(TokenKind.NAME); switch (operationToken.value) { case "query": return OperationTypeNode.QUERY; case "mutation": return OperationTypeNode.MUTATION; case "subscription": return OperationTypeNode.SUBSCRIPTION; } throw this.unexpected(operationToken); } /** * VariableDefinitions : ( VariableDefinition+ ) */ parseVariableDefinitions() { return this.optionalMany( TokenKind.PAREN_L, this.parseVariableDefinition, TokenKind.PAREN_R ); } /** * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? */ parseVariableDefinition() { return this.node(this._lexer.token, { kind: Kind.VARIABLE_DEFINITION, variable: this.parseVariable(), type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()), defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseConstValueLiteral() : undefined, directives: this.parseConstDirectives(), }); } /** * Variable : $ Name */ parseVariable() { const start = this._lexer.token; this.expectToken(TokenKind.DOLLAR); return this.node(start, { kind: Kind.VARIABLE, name: this.parseName(), }); } /** * ``` * SelectionSet : { Selection+ } * ``` */ parseSelectionSet() { return this.node(this._lexer.token, { kind: Kind.SELECTION_SET, selections: this.many( TokenKind.BRACE_L, this.parseSelection, TokenKind.BRACE_R ), }); } /** * Selection : * - Field * - FragmentSpread * - InlineFragment */ parseSelection() { return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); } /** * Field : Alias? Name Arguments? Directives? SelectionSet? * * Alias : Name : */ parseField() { const start = this._lexer.token; const nameOrAlias = this.parseName(); let alias; let name; if (this.expectOptionalToken(TokenKind.COLON)) { alias = nameOrAlias; name = this.parseName(); } else { name = nameOrAlias; } return this.node(start, { kind: Kind.FIELD, alias, name, arguments: this.parseArguments(false), directives: this.parseDirectives(false), selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined, }); } /** * Arguments[Const] : ( Argument[?Const]+ ) */ parseArguments(isConst) { const item = isConst ? this.parseConstArgument : this.parseArgument; return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R); } /** * Argument[Const] : Name : Value[?Const] */ parseArgument(isConst = false) { const start = this._lexer.token; const name = this.parseName(); this.expectToken(TokenKind.COLON); return this.node(start, { kind: Kind.ARGUMENT, name, value: this.parseValueLiteral(isConst), }); } parseConstArgument() { return this.parseArgument(true); } // Implements the parsing rules in the Fragments section. /** * Corresponds to both FragmentSpread and InlineFragment in the spec. * * FragmentSpread : ... FragmentName Directives? * * InlineFragment : ... TypeCondition? Directives? SelectionSet */ parseFragment() { const start = this._lexer.token; this.expectToken(TokenKind.SPREAD); const hasTypeCondition = this.expectOptionalKeyword("on"); if (!hasTypeCondition && this.peek(TokenKind.NAME)) { return this.node(start, { kind: Kind.FRAGMENT_SPREAD, name: this.parseFragmentName(), directives: this.parseDirectives(false), }); } return this.node(start, { kind: Kind.INLINE_FRAGMENT, typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), }); } /** * FragmentDefinition : * - fragment FragmentName on TypeCondition Directives? SelectionSet * * TypeCondition : NamedType */ parseFragmentDefinition() { var _this$_options; const start = this._lexer.token; this.expectKeyword("fragment"); // Legacy support for defining variables within fragments changes // the grammar of FragmentDefinition: // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet if ( ((_this$_options = this._options) === null || _this$_options === void 0 ? void 0 : _this$_options.allowLegacyFragmentVariables) === true ) { return this.node(start, { kind: Kind.FRAGMENT_DEFINITION, name: this.parseFragmentName(), variableDefinitions: this.parseVariableDefinitions(), typeCondition: (this.expectKeyword("on"), this.parseNamedType()), directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), }); } return this.node(start, { kind: Kind.FRAGMENT_DEFINITION, name: this.parseFragmentName(), typeCondition: (this.expectKeyword("on"), this.parseNamedType()), directives: this.parseDirectives(false), selectionSet: this.parseSelectionSet(), }); } /** * FragmentName : Name but not `on` */ parseFragmentName() { if (this._lexer.token.value === "on") { throw this.unexpected(); } return this.parseName(); } // Implements the parsing rules in the Values section. /** * Value[Const] : * - [~Const] Variable * - IntValue * - FloatValue * - StringValue * - BooleanValue * - NullValue * - EnumValue * - ListValue[?Const] * - ObjectValue[?Const] * * BooleanValue : one of `true` `false` * * NullValue : `null` * * EnumValue : Name but not `true`, `false` or `null` */ parseValueLiteral(isConst) { const token = this._lexer.token; switch (token.kind) { case TokenKind.BRACKET_L: return this.parseList(isConst); case TokenKind.BRACE_L: return this.parseObject(isConst); case TokenKind.INT: this._lexer.advance(); return this.node(token, { kind: Kind.INT, value: token.value, }); case TokenKind.FLOAT: this._lexer.advance(); return this.node(token, { kind: Kind.FLOAT, value: token.value, }); case TokenKind.STRING: case TokenKind.BLOCK_STRING: return this.parseStringLiteral(); case TokenKind.NAME: this._lexer.advance(); switch (token.value) { case "true": return this.node(token, { kind: Kind.BOOLEAN, value: true, }); case "false": return this.node(token, { kind: Kind.BOOLEAN, value: false, }); case "null": return this.node(token, { kind: Kind.NULL, }); default: return this.node(token, { kind: Kind.ENUM, value: token.value, }); } case TokenKind.DOLLAR: if (isConst) { this.expectToken(TokenKind.DOLLAR); if (this._lexer.token.kind === TokenKind.NAME) { const varName = this._lexer.token.value; throw syntaxError( this._lexer.source, token.start, `Unexpected variable "$${varName}" in constant value.` ); } else { throw this.unexpected(token); } } return this.parseVariable(); } throw this.unexpected(); } parseConstValueLiteral() { return this.parseValueLiteral(true); } parseStringLiteral() { const token = this._lexer.token; this._lexer.advance(); return this.node(token, { kind: Kind.STRING, value: token.value, block: token.kind === TokenKind.BLOCK_STRING, }); } /** * ListValue[Const] : * - [ ] * - [ Value[?Const]+ ] */ parseList(isConst) { const item = () => this.parseValueLiteral(isConst); return this.node(this._lexer.token, { kind: Kind.LIST, values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), }); } /** * ``` * ObjectValue[Const] : * - { } * - { ObjectField[?Const]+ } * ``` */ parseObject(isConst) { const item = () => this.parseObjectField(isConst); return this.node(this._lexer.token, { kind: Kind.OBJECT, fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R), }); } /** * ObjectField[Const] : Name : Value[?Const] */ parseObjectField(isConst) { const start = this._lexer.token; const name = this.parseName(); this.expectToken(TokenKind.COLON); return this.node(start, { kind: Kind.OBJECT_FIELD, name, value: this.parseValueLiteral(isConst), }); } // Implements the parsing rules in the Directives section. /** * Directives[Const] : Directive[?Const]+ */ parseDirectives(isConst) { const directives = []; while (this.peek(TokenKind.AT)) { directives.push(this.parseDirective(isConst)); } return directives; } parseConstDirectives() { return this.parseDirectives(true); } /** * ``` * Directive[Const] : @ Name Arguments[?Const]? * ``` */ parseDirective(isConst) { const start = this._lexer.token; this.expectToken(TokenKind.AT); return this.node(start, { kind: Kind.DIRECTIVE, name: this.parseName(), arguments: this.parseArguments(isConst), }); } // Implements the parsing rules in the Types section. /** * Type : * - NamedType * - ListType * - NonNullType */ parseTypeReference() { const start = this._lexer.token; let type; if (this.expectOptionalToken(TokenKind.BRACKET_L)) { const innerType = this.parseTypeReference(); this.expectToken(TokenKind.BRACKET_R); type = this.node(start, { kind: Kind.LIST_TYPE, type: innerType, }); } else { type = this.parseNamedType(); } if (this.expectOptionalToken(TokenKind.BANG)) { return this.node(start, { kind: Kind.NON_NULL_TYPE, type, }); } return type; } /** * NamedType : Name */ parseNamedType() { return this.node(this._lexer.token, { kind: Kind.NAMED_TYPE, name: this.parseName(), }); } // Implements the parsing rules in the Type Definition section. peekDescription() { return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING); } /** * Description : StringValue */ parseDescription() { if (this.peekDescription()) { return this.parseStringLiteral(); } } /** * ``` * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } * ``` */ parseSchemaDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("schema"); const directives = this.parseConstDirectives(); const operationTypes = this.many( TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R ); return this.node(start, { kind: Kind.SCHEMA_DEFINITION, description, directives, operationTypes, }); } /** * OperationTypeDefinition : OperationType : NamedType */ parseOperationTypeDefinition() { const start = this._lexer.token; const operation = this.parseOperationType(); this.expectToken(TokenKind.COLON); const type = this.parseNamedType(); return this.node(start, { kind: Kind.OPERATION_TYPE_DEFINITION, operation, type, }); } /** * ScalarTypeDefinition : Description? scalar Name Directives[Const]? */ parseScalarTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("scalar"); const name = this.parseName(); const directives = this.parseConstDirectives(); return this.node(start, { kind: Kind.SCALAR_TYPE_DEFINITION, description, name, directives, }); } /** * ObjectTypeDefinition : * Description? * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? */ parseObjectTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("type"); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseConstDirectives(); const fields = this.parseFieldsDefinition(); return this.node(start, { kind: Kind.OBJECT_TYPE_DEFINITION, description, name, interfaces, directives, fields, }); } /** * ImplementsInterfaces : * - implements `&`? NamedType * - ImplementsInterfaces & NamedType */ parseImplementsInterfaces() { return this.expectOptionalKeyword("implements") ? this.delimitedMany(TokenKind.AMP, this.parseNamedType) : []; } /** * ``` * FieldsDefinition : { FieldDefinition+ } * ``` */ parseFieldsDefinition() { return this.optionalMany( TokenKind.BRACE_L, this.parseFieldDefinition, TokenKind.BRACE_R ); } /** * FieldDefinition : * - Description? Name ArgumentsDefinition? : Type Directives[Const]? */ parseFieldDefinition() { const start = this._lexer.token; const description = this.parseDescription(); const name = this.parseName(); const args = this.parseArgumentDefs(); this.expectToken(TokenKind.COLON); const type = this.parseTypeReference(); const directives = this.parseConstDirectives(); return this.node(start, { kind: Kind.FIELD_DEFINITION, description, name, arguments: args, type, directives, }); } /** * ArgumentsDefinition : ( InputValueDefinition+ ) */ parseArgumentDefs() { return this.optionalMany( TokenKind.PAREN_L, this.parseInputValueDef, TokenKind.PAREN_R ); } /** * InputValueDefinition : * - Description? Name : Type DefaultValue? Directives[Const]? */ parseInputValueDef() { const start = this._lexer.token; const description = this.parseDescription(); const name = this.parseName(); this.expectToken(TokenKind.COLON); const type = this.parseTypeReference(); let defaultValue; if (this.expectOptionalToken(TokenKind.EQUALS)) { defaultValue = this.parseConstValueLiteral(); } const directives = this.parseConstDirectives(); return this.node(start, { kind: Kind.INPUT_VALUE_DEFINITION, description, name, type, defaultValue, directives, }); } /** * InterfaceTypeDefinition : * - Description? interface Name Directives[Const]? FieldsDefinition? */ parseInterfaceTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("interface"); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseConstDirectives(); const fields = this.parseFieldsDefinition(); return this.node(start, { kind: Kind.INTERFACE_TYPE_DEFINITION, description, name, interfaces, directives, fields, }); } /** * UnionTypeDefinition : * - Description? union Name Directives[Const]? UnionMemberTypes? */ parseUnionTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("union"); const name = this.parseName(); const directives = this.parseConstDirectives(); const types = this.parseUnionMemberTypes(); return this.node(start, { kind: Kind.UNION_TYPE_DEFINITION, description, name, directives, types, }); } /** * UnionMemberTypes : * - = `|`? NamedType * - UnionMemberTypes | NamedType */ parseUnionMemberTypes() { return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : []; } /** * EnumTypeDefinition : * - Description? enum Name Directives[Const]? EnumValuesDefinition? */ parseEnumTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("enum"); const name = this.parseName(); const directives = this.parseConstDirectives(); const values = this.parseEnumValuesDefinition(); return this.node(start, { kind: Kind.ENUM_TYPE_DEFINITION, description, name, directives, values, }); } /** * ``` * EnumValuesDefinition : { EnumValueDefinition+ } * ``` */ parseEnumValuesDefinition() { return this.optionalMany( TokenKind.BRACE_L, this.parseEnumValueDefinition, TokenKind.BRACE_R ); } /** * EnumValueDefinition : Description? EnumValue Directives[Const]? */ parseEnumValueDefinition() { const start = this._lexer.token; const description = this.parseDescription(); const name = this.parseEnumValueName(); const directives = this.parseConstDirectives(); return this.node(start, { kind: Kind.ENUM_VALUE_DEFINITION, description, name, directives, }); } /** * EnumValue : Name but not `true`, `false` or `null` */ parseEnumValueName() { if ( this._lexer.token.value === "true" || this._lexer.token.value === "false" || this._lexer.token.value === "null" ) { throw syntaxError( this._lexer.source, this._lexer.token.start, `${getTokenDesc( this._lexer.token )} is reserved and cannot be used for an enum value.` ); } return this.parseName(); } /** * InputObjectTypeDefinition : * - Description? input Name Directives[Const]? InputFieldsDefinition? */ parseInputObjectTypeDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("input"); const name = this.parseName(); const directives = this.parseConstDirectives(); const fields = this.parseInputFieldsDefinition(); return this.node(start, { kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, description, name, directives, fields, }); } /** * ``` * InputFieldsDefinition : { InputValueDefinition+ } * ``` */ parseInputFieldsDefinition() { return this.optionalMany( TokenKind.BRACE_L, this.parseInputValueDef, TokenKind.BRACE_R ); } /** * TypeSystemExtension : * - SchemaExtension * - TypeExtension * * TypeExtension : * - ScalarTypeExtension * - ObjectTypeExtension * - InterfaceTypeExtension * - UnionTypeExtension * - EnumTypeExtension * - InputObjectTypeDefinition */ parseTypeSystemExtension() { const keywordToken = this._lexer.lookahead(); if (keywordToken.kind === TokenKind.NAME) { switch (keywordToken.value) { case "schema": return this.parseSchemaExtension(); case "scalar": return this.parseScalarTypeExtension(); case "type": return this.parseObjectTypeExtension(); case "interface": return this.parseInterfaceTypeExtension(); case "union": return this.parseUnionTypeExtension(); case "enum": return this.parseEnumTypeExtension(); case "input": return this.parseInputObjectTypeExtension(); } } throw this.unexpected(keywordToken); } /** * ``` * SchemaExtension : * - extend schema Directives[Const]? { OperationTypeDefinition+ } * - extend schema Directives[Const] * ``` */ parseSchemaExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("schema"); const directives = this.parseConstDirectives(); const operationTypes = this.optionalMany( TokenKind.BRACE_L, this.parseOperationTypeDefinition, TokenKind.BRACE_R ); if (directives.length === 0 && operationTypes.length === 0) { throw this.unexpected(); } return this.node(start, { kind: Kind.SCHEMA_EXTENSION, directives, operationTypes, }); } /** * ScalarTypeExtension : * - extend scalar Name Directives[Const] */ parseScalarTypeExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("scalar"); const name = this.parseName(); const directives = this.parseConstDirectives(); if (directives.length === 0) { throw this.unexpected(); } return this.node(start, { kind: Kind.SCALAR_TYPE_EXTENSION, name, directives, }); } /** * ObjectTypeExtension : * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition * - extend type Name ImplementsInterfaces? Directives[Const] * - extend type Name ImplementsInterfaces */ parseObjectTypeExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("type"); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseConstDirectives(); const fields = this.parseFieldsDefinition(); if ( interfaces.length === 0 && directives.length === 0 && fields.length === 0 ) { throw this.unexpected(); } return this.node(start, { kind: Kind.OBJECT_TYPE_EXTENSION, name, interfaces, directives, fields, }); } /** * InterfaceTypeExtension : * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition * - extend interface Name ImplementsInterfaces? Directives[Const] * - extend interface Name ImplementsInterfaces */ parseInterfaceTypeExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("interface"); const name = this.parseName(); const interfaces = this.parseImplementsInterfaces(); const directives = this.parseConstDirectives(); const fields = this.parseFieldsDefinition(); if ( interfaces.length === 0 && directives.length === 0 && fields.length === 0 ) { throw this.unexpected(); } return this.node(start, { kind: Kind.INTERFACE_TYPE_EXTENSION, name, interfaces, directives, fields, }); } /** * UnionTypeExtension : * - extend union Name Directives[Const]? UnionMemberTypes * - extend union Name Directives[Const] */ parseUnionTypeExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("union"); const name = this.parseName(); const directives = this.parseConstDirectives(); const types = this.parseUnionMemberTypes(); if (directives.length === 0 && types.length === 0) { throw this.unexpected(); } return this.node(start, { kind: Kind.UNION_TYPE_EXTENSION, name, directives, types, }); } /** * EnumTypeExtension : * - extend enum Name Directives[Const]? EnumValuesDefinition * - extend enum Name Directives[Const] */ parseEnumTypeExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("enum"); const name = this.parseName(); const directives = this.parseConstDirectives(); const values = this.parseEnumValuesDefinition(); if (directives.length === 0 && values.length === 0) { throw this.unexpected(); } return this.node(start, { kind: Kind.ENUM_TYPE_EXTENSION, name, directives, values, }); } /** * InputObjectTypeExtension : * - extend input Name Directives[Const]? InputFieldsDefinition * - extend input Name Directives[Const] */ parseInputObjectTypeExtension() { const start = this._lexer.token; this.expectKeyword("extend"); this.expectKeyword("input"); const name = this.parseName(); const directives = this.parseConstDirectives(); const fields = this.parseInputFieldsDefinition(); if (directives.length === 0 && fields.length === 0) { throw this.unexpected(); } return this.node(start, { kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, name, directives, fields, }); } /** * ``` * DirectiveDefinition : * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations * ``` */ parseDirectiveDefinition() { const start = this._lexer.token; const description = this.parseDescription(); this.expectKeyword("directive"); this.expectToken(TokenKind.AT); const name = this.parseName(); const args = this.parseArgumentDefs(); const repeatable = this.expectOptionalKeyword("repeatable"); this.expectKeyword("on"); const locations = this.parseDirectiveLocations(); return this.node(start, { kind: Kind.DIRECTIVE_DEFINITION, description, name, arguments: args, repeatable, locations, }); } /** * DirectiveLocations : * - `|`? DirectiveLocation * - DirectiveLocations | DirectiveLocation */ parseDirectiveLocations() { return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation); } /* * DirectiveLocation : * - ExecutableDirectiveLocation * - TypeSystemDirectiveLocation * * ExecutableDirectiveLocation : one of * `QUERY` * `MUTATION` * `SUBSCRIPTION` * `FIELD` * `FRAGMENT_DEFINITION` * `FRAGMENT_SPREAD` * `INLINE_FRAGMENT` * * TypeSystemDirectiveLocation : one of * `SCHEMA` * `SCALAR` * `OBJECT` * `FIELD_DEFINITION` * `ARGUMENT_DEFINITION` * `INTERFACE` * `UNION` * `ENUM` * `ENUM_VALUE` * `INPUT_OBJECT` * `INPUT_FIELD_DEFINITION` */ parseDirectiveLocation() { const start = this._lexer.token; const name = this.parseName(); if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) { return name; } throw this.unexpected(start); } // Core parsing utility functions /** * Returns a node that, if configured to do so, sets a "loc" field as a * location object, used to identify the place in the source that created a * given parsed object. */ node(startToken, node) { var _this$_options2; if ( ((_this$_options2 = this._options) === null || _this$_options2 === void 0 ? void 0 : _this$_options2.noLocation) !== true ) { node.loc = new Location( startToken, this._lexer.lastToken, this._lexer.source ); } return node; } /** * Determines if the next token is of a given kind */ peek(kind) { return this._lexer.token.kind === kind; } /** * If the next token is of the given kind, return that token after advancing the lexer. * Otherwise, do not change the parser state and throw an error. */ expectToken(kind) { const token = this._lexer.token; if (token.kind === kind) { this._lexer.advance(); return token; } throw syntaxError( this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.` ); } /** * If the next token is of the given kind, return "true" after advancing the lexer. * Otherwise, do not change the parser state and return "false". */ expectOptionalToken(kind) { const token = this._lexer.token; if (token.kind === kind) { this._lexer.advance(); return true; } return false; } /** * If the next token is a given keyword, advance the lexer. * Otherwise, do not change the parser state and throw an error. */ expectKeyword(value) { const token = this._lexer.token; if (token.kind === TokenKind.NAME && token.value === value) { this._lexer.advance(); } else { throw syntaxError( this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.` ); } } /** * If the next token is a given keyword, return "true" after advancing the lexer. * Otherwise, do not change the parser state and return "false". */ expectOptionalKeyword(value) { const token = this._lexer.token; if (token.kind === TokenKind.NAME && token.value === value) { this._lexer.advance(); return true; } return false; } /** * Helper function for creating an error when an unexpected lexed token is encountered. */ unexpected(atToken) { const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; return syntaxError( this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.` ); } /** * Returns a possibly empty list of parse nodes, determined by the parseFn. * This list begins with a lex token of openKind and ends with a lex token of closeKind. * Advances the parser to the next lex token after the closing token. */ any(openKind, parseFn, closeKind) { this.expectToken(openKind); const nodes = []; while (!this.expectOptionalToken(closeKind)) { nodes.push(parseFn.call(this)); } return nodes; } /** * Returns a list of parse nodes, determined by the parseFn. * It can be empty only if open token is missing otherwise it will always return non-empty list * that begins with a lex token of openKind and ends with a lex token of closeKind. * Advances the parser to the next lex token after the closing token. */ optionalMany(openKind, parseFn, closeKind) { if (this.expectOptionalToken(openKind)) { const nodes = []; do { nodes.push(parseFn.call(this)); } while (!this.expectOptionalToken(closeKind)); return nodes; } return []; } /** * Returns a non-empty list of parse nodes, determined by the parseFn. * This list begins with a lex token of openKind and ends with a lex token of closeKind. * Advances the parser to the next lex token after the closing token. */ many(openKind, parseFn, closeKind) { this.expectToken(openKind); const nodes = []; do { nodes.push(parseFn.call(this)); } while (!this.expectOptionalToken(closeKind)); return nodes; } /** * Returns a non-empty list of parse nodes, determined by the parseFn. * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. * Advances the parser to the next lex token after last item in the list. */ delimitedMany(delimiterKind, parseFn) { this.expectOptionalToken(delimiterKind); const nodes = []; do { nodes.push(parseFn.call(this)); } while (this.expectOptionalToken(delimiterKind)); return nodes; } }
JavaScript
class VigenereCipheringMachine { constructor(reverseFlag = true) { this.reverseFlag = reverseFlag; } encrypt(text, code) { if (!text || !code) throw new Error('Incorrect arguments!'); let resp = ''; let codeStr = []; for (let i in text) codeStr.push(code[i % code.length].toUpperCase().charCodeAt() - 65); let counter = 0; for (let symbol of text) { let temp; if (symbol.match(/[a-zA-Z]/)) { temp = symbol.toUpperCase().charCodeAt() + codeStr[counter]; temp = temp > 90 ? temp - 26 : temp; temp = String.fromCharCode(temp); counter++; } else temp = symbol; resp += temp; } if (!this.reverseFlag) resp = resp.split("").reverse().join(""); return resp; } decrypt(text, code) { if (!text || !code) throw new Error('Incorrect arguments!'); let resp = ''; let codeStr = []; for (let i in text) codeStr.push(code[i % code.length].toUpperCase().charCodeAt() - 65); let counter = 0; for (let symbol of text) { let temp; if (symbol.match(/[a-zA-Z]/)) { temp = symbol.toUpperCase().charCodeAt() - codeStr[counter]; temp = temp < 65 ? temp + 26 : temp; temp = String.fromCharCode(temp); counter++; } else temp = symbol; resp += temp; } if (!this.reverseFlag) resp = resp.split("").reverse().join(""); return resp; } }
JavaScript
class InputMismatchException extends RecognitionException { constructor(recognizer) { super({message: "", recognizer: recognizer, input: recognizer.getInputStream(), ctx: recognizer._ctx}); this.offendingToken = recognizer.getCurrentToken(); } }
JavaScript
class EJLaTeX { constructor({data}) { //Get the saved data if exists this.data = data.math; } static get toolbox() { return { title: "Math", //icon: '<svg width="17" height="15" viewBox="0 0 336 276" xmlns="http://www.w3.org/2000/svg"><path d="M291 150V79c0-19-15-34-34-34H79c-19 0-34 15-34 34v42l67-44 81 72 56-29 42 30zm0 52l-43-30-56 30-81-67-66 39v23c0 19 15 34 34 34h178c17 0 31-13 34-29zM79 0h178c44 0 79 35 79 79v118c0 44-35 79-79 79H79c-44 0-79-35-79-79V79C0 35 35 0 79 0z"/></svg>' icon: '<svg id="Layer_1" enable-background="new 0 0 506.1 506.1" height="512" viewBox="0 0 506.1 506.1" width="512" xmlns="http://www.w3.org/2000/svg"><path d="m489.609 0h-473.118c-9.108 0-16.491 7.383-16.491 16.491v473.118c0 9.107 7.383 16.491 16.491 16.491h473.119c9.107 0 16.49-7.383 16.49-16.491v-473.118c0-9.108-7.383-16.491-16.491-16.491zm-16.49 473.118h-440.138v-440.137h440.138z"/><path d="m367.278 240.136v-62.051c0-8.836-7.163-16-16-16s-16 7.164-16 16v147.377c0 15.024 18.993 21.77 28.457 10.03 34.691 18.107 77.146-6.988 77.146-46.831.001-37.966-39-63.416-73.603-48.525zm20.802 69.327c-11.47 0-20.802-9.332-20.802-20.802s9.332-20.802 20.802-20.802 20.802 9.332 20.802 20.802-9.332 20.802-20.802 20.802z"/><path d="m112.397 200.262h-14.014c-8.836 0-16 7.164-16 16s7.164 16 16 16h14.014c8.291 0 15.037 6.746 15.037 15.037v4.998c-30.589-10.389-62.216 12.536-62.216 44.609 0 34.402 35.954 57.331 67.13 42.629 10.128 9.747 27.086 2.537 27.086-11.521v-80.715c0-25.936-21.101-47.037-47.037-47.037zm-.071 111.752c-8.331 0-15.108-6.777-15.108-15.108s6.777-15.108 15.108-15.108 15.108 6.777 15.108 15.108-6.778 15.108-15.108 15.108z"/><path d="m287.786 243.114c-6.248-6.248-16.379-6.249-22.627 0l-18.11 18.11-18.11-18.11c-6.249-6.249-16.379-6.249-22.627 0-6.249 6.249-6.249 16.379 0 22.627l18.11 18.11-18.11 18.11c-6.248 6.248-6.248 16.379 0 22.627s16.378 6.249 22.627 0l18.11-18.11 18.11 18.11c6.246 6.248 16.377 6.249 22.627 0 6.249-6.249 6.249-16.379 0-22.627l-18.11-18.11 18.11-18.11c6.249-6.248 6.249-16.379 0-22.627z"/></svg>' }; } render (){ //Create all the DOM elements const wrapper = document.createElement('div'); const preview = document.createElement('p'); const input = document.createElement('input'); if(typeof katex === "undefined") { let errorMessageSpan = document.createElement("span"); errorMessageSpan.className = "errorMessage"; errorMessageSpan.innerText = "[Erorr] KaTeX is not found! Add KaTeX to this webpage to continue!" return errorMessageSpan; } wrapper.classList.add('math-input-wrapper'); preview.classList.add('math-preview'); input.classList.add('math-input'); //Load the data if exists input.value = this.data ? this.data : ''; //Set the placeholder text for LaTeX expression input input.setAttribute("placeholder", "Enter LaTeX here"); //Will render LaTeX if there is any in saved data katex.render(input.value, preview, { throwOnError: false }); input.addEventListener('keyup', (e) => { //Prevent default actions e.preventDefault(); //Render LaTeX expression katex.render(input.value, preview, { throwOnError: false }); }); wrapper.appendChild(preview); wrapper.appendChild(input); return wrapper; } save(blockContent) { return { math: blockContent.childNodes[1].value }; } }
JavaScript
class AddProperty extends expressionEvaluator_1.ExpressionEvaluator { /** * Initializes a new instance of the [AddProperty](xref:adaptive-expressions.AddProperty) class. */ constructor() { super(expressionType_1.ExpressionType.AddProperty, AddProperty.evaluator(), returnType_1.ReturnType.Object, AddProperty.validator); } /** * @private */ static evaluator() { return functionUtils_1.FunctionUtils.applyWithError((args) => { let error; const temp = args[0]; const prop = String(args[1]); if (prop in temp) { error = `${prop} already exists`; } else { temp[String(args[1])] = args[2]; } return { value: temp, error }; }); } /** * @private */ static validator(expression) { functionUtils_1.FunctionUtils.validateOrder(expression, undefined, returnType_1.ReturnType.Object, returnType_1.ReturnType.String, returnType_1.ReturnType.Object); } }
JavaScript
class AuthenticatedDataSource extends RemoteGraphQLDataSource { willSendRequest({ request, context }) { if (context.token) { request.http.headers.set(HEADER_FOR_AUTH, context.token) } } // didReceiveResponse({ response, request, context }) { // console.log(response) // return response // } }
JavaScript
class RedwoodEvents extends PolymerElement { static get properties() { return { /** * ping is useful for testing latency and can be turned on/off * with `togglePing()` */ ping: { type: Boolean, value: false }, _master: { type: Boolean, value: false }, _sendTime: { type: Object, value: 0 }, _roundTripTimes: { type: Array, value: () => { return []; } }, _avgPingTime: { type: Number, computed: '_computeAvgPingTime(_roundTripTimes.*)' }, _connectionStatus: { type: String, computed: '_computeConnectionStatus(socket.*, _roundTripTimes.*)' }, /* Bound by the otree-constants component */ _debug: { type: Boolean /** * Fired when a message is received on the WebSocket. * * @event event * @param {event} otree_redwood.models.Event.message */ } }; } static get template() { return html` <otree-constants id="constants" _debug="{{ _debug }}"></otree-constants> <template is="dom-if" if="[[ _master ]]"> <template is="dom-if" if="[[ _debug ]]"> <div class="well"> <p>Connected: [[ _connectionStatus ]]</p> <p>Ping: [[ _avgPingTime ]]</p> <button type="button" on-click="togglePing" hidden$="[[ ping ]]">Start</button> <button type="button" on-click="togglePing" hidden$="[[ !ping ]]">Stop</button> </div> </template> </template> `; } ready() { super.ready(); if (socket === null) { this._master = true; let protocol = 'ws://'; if (window.location.protocol === 'https:') { protocol = 'wss://'; } const addr = protocol + window.location.host + '/redwood' + '/app-name/' + this.$.constants.appName + '/group/' + this.$.constants.group.pk + '/participant/' + this.$.constants.participantCode + '/'; socket = new ReconnectingWebSocket(addr, null, { timeoutInterval: 10000 }); socket.onerror = this._onError.bind(this); socket.onopen = this._onOpen.bind(this); socket.onmessage = this._onMessage.bind(this); socket.onclose = this._onClose.bind(this); } this.socket = socket; this.pending = []; listeners.push(this); } disconnectedCallback() { super.disconnectedCallback(); listeners.splice(listeners.indexOf(this), 1); } _onOpen() { this.socket = socket; listeners.forEach(l => { l.pending.forEach(msg => { socket.send(msg); }); }); if (this._debug) { this._sendPing(); } } _onClose() { this.socket = socket; } _onError(err) { this.socket = socket; console.error(err); } _onMessage(message) { this.socket = socket; const event = JSON.parse(message.data); if (event.channel == 'ping') { const rtt = Date.now() - event.timestamp; this.push('_roundTripTimes', rtt); if (this._roundTripTimes.length > 10) { this.splice('_roundTripTimes', 0, 1); } return; } listeners.forEach(l => { l.dispatchEvent(new CustomEvent('event', { detail: event })); }); } /** * Toggle `ping` on/off. */ togglePing() { this.ping = !this.ping; if (this.ping) { this._sendPing(); } } _sendPing() { this.socket = socket; if (socket.readyState == 1) { socket.send(JSON.stringify({ 'channel': 'ping', 'timestamp': Date.now(), 'avgping_time': this._avgPingTime })); } if (this.ping) { window.setTimeout(this._sendPing.bind(this), 1000); } } _computeAvgPingTime() { if (this._roundTripTimes.length == 0) { return NaN; } const sum = this._roundTripTimes.reduce((acc, val) => { return acc + val; }, 0); return Math.floor(sum / this._roundTripTimes.length); } _computeConnectionStatus() { if (!this.socket) return; if (this.socket.readyState == 1) { return 'connected'; } return 'not connected'; } /** * Send a message to the server. * * @param {String} channel * @param {Object} value */ send(channel, value) { const msg = JSON.stringify({ 'channel': channel, 'payload': value }); if (socket.readyState != 1) { this.pending.push(msg); return; } socket.send(msg); } }
JavaScript
class App extends Component { /** */ constructor(props) { super(props); this.i18n = i18n; } /** * Set i18n language on component mount */ componentDidMount() { const { language } = this.props; this.i18n.changeLanguage(language); } /** * Update the i18n language if it is changed */ componentDidUpdate(prevProps) { const { language } = this.props; if (prevProps.language !== language) { this.i18n.changeLanguage(language); } } /** * render * @return {String} - HTML markup for the component */ render() { const { isFullscreenEnabled, setWorkspaceFullscreen, classes, isWorkspaceAddVisible, isWorkspaceControlPanelVisible, theme, translations, } = this.props; Object.keys(translations).forEach((lng) => { this.i18n.addResourceBundle(lng, 'translation', translations[lng], true, true); }); return ( <div className={classNames(classes.background, ns('app'))}> <I18nextProvider i18n={this.i18n}> <MuiThemeProvider theme={createMuiTheme(theme)}> <Fullscreen enabled={isFullscreenEnabled} onChange={setWorkspaceFullscreen} > { isWorkspaceAddVisible ? <WorkspaceAdd /> : <Workspace /> } </Fullscreen> { isWorkspaceControlPanelVisible && <WorkspaceControlPanel /> } </MuiThemeProvider> </I18nextProvider> </div> ); } }
JavaScript
class BruteForceCollisionDetection { constructor(options) { this.options = Object.assign({ autoResolve: true }, options); this.collisionPairs = {}; } init(options) { this.gameEngine = options.gameEngine; } findCollision(o1, o2) { // static objects don't collide if (o1.isStatic && o2.isStatic) return false; // allow a collision checker function if (typeof o1.collidesWith === 'function') { if (!o1.collidesWith(o2)) return false; } // radius-based collision if (this.options.collisionDistance) { differenceVector.copy(o1.position).subtract(o2.position); return differenceVector.length() < this.options.collisionDistance; } // check for no-collision first let o1Box = getBox(o1); let o2Box = getBox(o2); if (o1Box.xMin > o2Box.xMax || o1Box.yMin > o2Box.yMax || o2Box.xMin > o1Box.xMax || o2Box.yMin > o1Box.yMax) return false; if (!this.options.autoResolve) return true; // need to auto-resolve let shiftY1 = o2Box.yMax - o1Box.yMin; let shiftY2 = o1Box.yMax - o2Box.yMin; let shiftX1 = o2Box.xMax - o1Box.xMin; let shiftX2 = o1Box.xMax - o2Box.xMin; let smallestYShift = Math.min(Math.abs(shiftY1), Math.abs(shiftY2)); let smallestXShift = Math.min(Math.abs(shiftX1), Math.abs(shiftX2)); // choose to apply the smallest shift which solves the collision if (smallestYShift < smallestXShift) { if (o1Box.yMin > o2Box.yMin && o1Box.yMin < o2Box.yMax) { if (o2.isStatic) o1.position.y += shiftY1; else if (o1.isStatic) o2.position.y -= shiftY1; else { o1.position.y += shiftY1 / 2; o2.position.y -= shiftY1 / 2; } } else if (o1Box.yMax > o2Box.yMin && o1Box.yMax < o2Box.yMax) { if (o2.isStatic) o1.position.y -= shiftY2; else if (o1.isStatic) o2.position.y += shiftY2; else { o1.position.y -= shiftY2 / 2; o2.position.y += shiftY2 / 2; } } o1.velocity.y = 0; o2.velocity.y = 0; } else { if (o1Box.xMin > o2Box.xMin && o1Box.xMin < o2Box.xMax) { if (o2.isStatic) o1.position.x += shiftX1; else if (o1.isStatic) o2.position.x -= shiftX1; else { o1.position.x += shiftX1 / 2; o2.position.x -= shiftX1 / 2; } } else if (o1Box.xMax > o2Box.xMin && o1Box.xMax < o2Box.xMax) { if (o2.isStatic) o1.position.x -= shiftX2; else if (o1.isStatic) o2.position.x += shiftX2; else { o1.position.x -= shiftX2 / 2; o2.position.x += shiftX2 / 2; } } o1.velocity.x = 0; o2.velocity.x = 0; } return true; } // check if pair (id1, id2) have collided checkPair(id1, id2) { let objects = this.gameEngine.world.objects; let o1 = objects[id1]; let o2 = objects[id2]; // make sure that objects actually exist. might have been destroyed if (!o1 || !o2) return; let pairId = [id1, id2].join(','); if (this.findCollision(o1, o2)) { if (!(pairId in this.collisionPairs)) { this.collisionPairs[pairId] = true; this.gameEngine.emit('collisionStart', { o1, o2 }); } } else if (pairId in this.collisionPairs) { this.gameEngine.emit('collisionStop', { o1, o2 }); delete this.collisionPairs[pairId]; } } // detect by checking all pairs detect() { let objects = this.gameEngine.world.objects; let keys = Object.keys(objects); // delete non existant object pairs for (let pairId in this.collisionPairs) if (this.collisionPairs.hasOwnProperty(pairId)) if (keys.indexOf(pairId.split(',')[0]) === -1 || keys.indexOf(pairId.split(',')[1]) === -1) delete this.collisionPairs[pairId]; // check all pairs for (let k1 of keys) for (let k2 of keys) if (k2 > k1) this.checkPair(k1, k2); } }
JavaScript
class Sequence { /** * validPayload * * @param {object} payload - is the payload that was just recieved by the system * @param {object} incoming - is the payload that was modeled in the system. * @return {array} */ static validPayload(payload, incoming) { var keys = Object.keys(incoming); for (let key of keys) { if (payload[key] === undefined) { return false; } } return true; } /** * reset the sequence head t * */ reset() { this.head = 0; } constructor() { this.chain = []; this.head = 0; // head must be within the bounds of the array; // turns true when the previous relay call made the head variable goto 0 this.looped = false; } _nextHead() { if (this.head + 1 >= this.chain.length) { this.looped = true; this.head = 0; return this.head; } else { this.looped = false; this.head++; return this.head; } } /** * Adds the relay list to the end of the chain * * @param {array} relays - an array of relay objects * @return {Sequence} */ addRelay(relays) { this.chain.push(relays); return this; } /** * Returns an array of the payloads that need to be emitted next in the sequence * * @param {object} payload - The incoming object that will continue the sequence * @return {array} - If given the correct payload, will return a list of objects for the outgoing seqence. */ relay(payload) { var parent = this; var activeRelays = _.filter(this.chain[this.head], function (rel) { return Relay.looseEqual(rel.incoming, payload); }); if (activeRelays.length !== 0) { this._nextHead(); return _.map(activeRelays, function (relay) { return relay.outgoing; }); } return []; } }
JavaScript
class DeviceOrchestrator { constructor(options) { this.io = options.io; this.events = {}; this.sequences = {}; // The home of the hooks this.brh = []; this.arh = []; this.bbh = []; this.abh = []; // contains the this.activeSequences = {}; } defineSequence(name) { this.sequences[name] = new Sequence(); this.as = name; return this.sequences[name]; } trip(seqName) { console.log(`Tripping the next sequence ${seqName}`); var self = this; self.activeSequences[seqName] = self.sequences[seqName]; } /** * Attach a custom listener to the Event System. */ on(event, fn) { this.events[event] = fn; } /** * Broadcast a message to all sockets attached to the socket io evt system */ emit() { var args = [].splice.call(arguments, 0); this.io.emit.apply(this.io, args); } /** * Takes a list of seqences that must be joined */ listen(seqOrder, head) { var self = this; self.seqenceOrder = seqOrder; self.headName = head; self.activeSequences[seqOrder[0]] = self.sequences[seqOrder[0]]; self.io.on('connection', function (socket) { // attaching the events _.each(self.events, function (fn, eventName) { socket.on(eventName, fn.bind(socket)); }); socket.on('dev:trigger', function (ipl) { var cont = self._beforeRelayHooks(ipl); if (!cont) return; // TODO: make this return outgoing paloads for all active sequences var outgoingPayloads = _.map(self._activeSequences(), (seq) => { return seq.relay(ipl); }); outgoingPayloads = _.flatten(outgoingPayloads); console.log("outgoing payloads", outgoingPayloads); cont = self._afterRelayHooks(ipl); if (!cont) return; _.each(outgoingPayloads, function (opl) { var cont = self._beforeBroadcastHooks(opl); if (!cont) return; socket.broadcast.emit('dev:command', opl); cont = self._afterBroadcastHooks(opl); if (!cont) return; }); }); }); } // Where other programs can define extra functionality to the // RelayNet beforeRelayHook (fn) { this._addHook('brh', fn); } afterRelayHook (fn) { this._addHook('arh', fn); } beforeBroadcastHook (fn) { this._addHook('bbh', fn); } afterBroadcastHook (fn) { this._addHook('abh', fn); } /*********** PRIVATE METHODS ************/ /** * Returns a list of the sequences that have been tripped */ _activeSequences() { return _.map(this.activeSequences, (seq, name) => { return seq; }); } _addHook(lst, fn) { this[lst].push(fn); } _runHooks(map, payload) { var ogSize = this[map].length; var outcome = _.filter(this[map], function (fn) { return fn(payload); }); if (ogSize != outcome.length) return false; return true; } _beforeRelayHooks (payload) { return this._runHooks("brh", payload); } _afterRelayHooks (payload) { return this._runHooks("arh", payload); } _beforeBroadcastHooks (payload) { return this._runHooks("bbh", payload); } _afterBroadcastHooks (payload) { return this._runHooks("abh", payload); } }
JavaScript
class DB { viewDepartments(){ return db.query('SELECT * FROM departments'); } viewRoles(){ return db.query('SELECT * FROM roles r JOIN departments d ON r.department_id=d.id') } viewEmployees(){ return db.query('SELECT * FROM employees e JOIN roles r ON e.role_id=r.id') } addDepartment(data){ return db.query(`INSERT INTO departments SET ?`, data) // expect object with all columns } addRole(data){ return db.query(`INSERT INTO roles SET ?`, data) } addEmployee(data){ return db.query(`INSERT INTO employees SET ?`, data) } updateEmployee(data){ return db.query(`UPDATE employees SET role_id=? WHERE first_name=?`, data) } deleteDepartment(data){ return db.query(`DELETE FROM departments WHERE department_name=?`, data) } deleteRole(data){ return db.query(`DELETE FROM roles WHERE title=?`, data) } deleteEmployee(data){ return db.query(`DELETE FROM employees WHERE first_name=?`, data) } findId(name, table, column){ return db.query(`SELECT id FROM ${table} WHERE ${column}='${name}'`) } }
JavaScript
class ElizaBotController extends RPCPhantomWorker { constructor() { super(() => new Worker("./ElizaBot.worker", { type: "module" })); } /** * Requests a welcome message. * * Note: This can be called multiple times without side-effects. * * @return {Promise<string>} */ async start() { return this.call("start"); } /** * Requests a reply. * * @return {Promise<string>} */ async reply(text) { return this.call("reply", { text }); } /** * Requests a goodbye message. * * Note: This can be called multiple times without side-effects. * * @return {Promise<string>} */ async bye() { return this.call("bye"); } }
JavaScript
class Skylink extends SkylinkPublicInterface { /** * @description Creates a SkylinkJS instance. * @param {initOptions} options - Skylink authentication and initialisation configuration options. * @private */ constructor(options) { super(); /** * @description Init options passed to API server to set certain values. * @type {initOptions} * @private */ const parsedOptions = new SkylinkAPIServer().init(options); Skylink.setInitOptions(parsedOptions); } /** * @description Method that retrieves the Skylink state. * @param {SkylinkRoom.id} roomKey - The id/key of the room. * @return {SkylinkState| Object} * @private */ static getSkylinkState(roomKey = null) { if (roomKey) { return skylinkStates.getState(roomKey); } return skylinkStates.getAllStates(); } /** * @description Method that sets the Skylink state keyed by room id. * @param {SkylinkState} state * @param {SkylinkRoom.id} roomKey - The id/key of the room. * @private */ static setSkylinkState(state, roomKey) { if (roomKey) { skylinkStates.setState(state); } } // eslint-disable-next-line consistent-return static removeSkylinkState(roomKey) { if (roomKey) { return skylinkStates.removeStateByRoomId(roomKey); } } // eslint-disable-next-line consistent-return static clearRoomStateFromSingletons(roomKey) { if (roomKey) { return skylinkStates.clearRoomStateFromSingletons(roomKey); } } /** * @description Method that retrieves the complete initOptions values (default + user specified). * @return {initOptions} * @private */ static getInitOptions() { return initOptions; } /** * @description Method that stores the complete initOptions values (default + user specified). * @param {initOptions} options * @private */ static setInitOptions(options) { initOptions = options; } /** * @description Method that stores the initOptions specified by the user. * @param {initOptions} options * @private */ static setUserInitOptions(options) { userInitOptions = options; } /** * @description Method that retrieves the initOptions specified by the user. * @private */ static getUserInitOptions() { return userInitOptions; } /** * @description Logs an error when Skylink state is not found for a roomKey. * @param {String} keyOrName - The id/key of the room or the room name. * @private */ static logNoRoomState(keyOrName) { SkylinkLogger.log.ERROR(`${messages.ROOM_STATE.NOT_FOUND} - ${keyOrName}`); } }
JavaScript
class SearchRecord { constructor() { this.cursor = 0 this.record = null } setCursor(val) { this.cursor = val } setRecord(val) { this.cursor = 0 this.record = deepcopy(val) debug('Record.length', this.record.length) } getNext(n) { let ans = [] let length = this.record.length for (let i = 0; i < n; i++) { let index = this.cursor + i if (index < length) { ans.push(this.record[index]) } } this.cursor = this.cursor + n debug('cursor', this.cursor, 'length', length) let noMore = false if (this.cursor >= length) { noMore = true } return { result: ans, noMore: noMore } } }
JavaScript
class ChannelGroup extends Component { constructor(props) { super(props); this.groupRef = null; this.state = { scrollLeft: 0, }; } componentDidUpdate() { this.considerScroll(); } considerScroll = () => { if (this.props.playState === "playing" && this.groupRef) { const scrolldiff = Math.abs(this.state.scrollLeft - this.groupRef.scrollLeft); if (scrolldiff > 10) { // do it only once for all channels this.groupRef.scrollLeft = this.state.scrollLeft; } } } reportProgress = (progress) => { // check progress to do autoscrolling const progressPx = secondsToPixels(progress, this.props.resolution); if (progressPx > this.groupRef.scrollLeft + this.groupRef.clientWidth) { this.setState({ scrollLeft: progressPx }); } else if (progressPx < this.groupRef.scrollLeft) { this.setState({ scrollLeft: progressPx }); } } render() { const { allchannelIds, ...passthruProps } = this.props; const channelComponents = allchannelIds .map((channelId) => ( <ChannelContainer {...passthruProps} className="ChannelContainer" channelId={channelId} key={channelId} reportProgress={this.reportProgress} />)); return ( <ChannelGroupWrapper className="ChannelGroupWrapper" drawerWidth={this.props.drawerWidth || 0} ref={(ref) => this.groupRef = ref}> <TimeScaleInSecs className="TimeScaleInSecs" maxDuration={this.props.maxDuration} resolution={this.props.resolution} theme={this.props.theme} /> {channelComponents} {this.props.isLoadingShow && <LoadProgressView disableShrink /> } </ChannelGroupWrapper> ); } }
JavaScript
class PDFAbstractReference { toString() { throw new Error('Must be implemented by subclasses'); } }
JavaScript
class CheckoutForm extends React.Component { constructor(props) { super(props) this.state = { name: '', card: '', street: '', apt: '', city: '', state: '', zipCode: '', email: '' } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } componentDidMount() { let user = this.props.user this.setState({ name: user.name || '', card: user.paymentInformation || '', street: user.street || '', apt: user.apt || '', city: user.city || '', state: user.state || '', zipCode: user.zipCode || '', email: user.email || '' }) } handleChange(event) { this.setState({[event.target.name]: event.target.value}) } handleSubmit(event) { event.preventDefault() const id = this.props.user.id const status = 'shipped' const address = { street: this.state.street, apt: this.state.apt || null, city: this.state.city, state: this.state.state, zipCode: this.state.zipCode } this.props.submitCart( this.props.cart, status, this.state.email, address, id ) this.props.history.push(`${this.props.location.pathname}/thank-you`) } render() { return ( <div id="formWrapper"> <form onSubmit={this.handleSubmit} id="checkoutForm"> <label htmlFor="name">Name:</label> <input onChange={this.handleChange} name="name" type="text" value={this.state.name} placeholder="Enter" required /> <label htmlFor="card">Card number:</label> <input onChange={this.handleChange} name="card" type="text" value={this.state.card} placeholder="Enter name" required /> <label htmlFor="email">Email:</label> <input onChange={this.handleChange} name="email" type="email" value={this.state.email} placeholder="Enter email" required /> <label htmlFor="street">Street:</label> <input onChange={this.handleChange} name="street" type="text" value={this.state.street} placeholder="Enter street" /> <label htmlFor="apt">Apt/Unit:</label> <input onChange={this.handleChange} name="apt" type="text" value={this.state.apt} placeholder="Enter apartment/unit number" /> <label htmlFor="city">City:</label> <input onChange={this.handleChange} name="city" type="text" value={this.state.city} placeholder="Enter city" /> <label htmlFor="state">State:</label> <input onChange={this.handleChange} name="state" type="text" value={this.state.state} placeholder="Enter state" /> <label htmlFor="zipCode">Zip Code:</label> <input onChange={this.handleChange} name="zipCode" type="text" value={this.state.zipCode} placeholder="Enter zipcode" /> <button type="submit">Submit</button> </form> </div> ) } }
JavaScript
class Keyboard { constructor (selectionWatcher) { eventable(this) this.selectionWatcher = selectionWatcher } dispatchKeyEvent (event, target, notifyCharacterEvent) { switch (event.keyCode) { case this.key.left: return this.notify(target, 'left', event) case this.key.right: return this.notify(target, 'right', event) case this.key.up: return this.notify(target, 'up', event) case this.key.down: return this.notify(target, 'down', event) case this.key.tab: if (event.shiftKey) return this.notify(target, 'shiftTab', event) return this.notify(target, 'tab', event) case this.key.esc: return this.notify(target, 'esc', event) case this.key.backspace: this.preventContenteditableBug(target, event) return this.notify(target, 'backspace', event) case this.key.delete: this.preventContenteditableBug(target, event) return this.notify(target, 'delete', event) case this.key.enter: if (event.shiftKey) return this.notify(target, 'shiftEnter', event) return this.notify(target, 'enter', event) case this.key.ctrl: case this.key.shift: case this.key.alt: return // Metakey case 224: // Firefox: 224 case 17: // Opera: 17 case 91: // Chrome/Safari: 91 (Left) case 93: // Chrome/Safari: 93 (Right) return default: // Added here to avoid using fall-through in the switch // when b or i are pressed without ctrlKey or metaKey if (event.keyCode === this.key.b && (event.ctrlKey || event.metaKey)) { return this.notify(target, 'bold', event) } if (event.keyCode === this.key.i && (event.ctrlKey || event.metaKey)) { return this.notify(target, 'italic', event) } this.preventContenteditableBug(target, event) if (!notifyCharacterEvent) return // Don't notify character events as long as either the ctrl or // meta key are pressed. // see: https://github.com/livingdocsIO/editable.js/pull/125 if (!event.ctrlKey && !event.metaKey) return this.notify(target, 'character', event) } } preventContenteditableBug (target, event) { if (!contenteditableSpanBug) return if (event.ctrlKey || event.metaKey) return // This fixes a strange webkit bug that can be reproduced as follows: // // 1. A node used within a contenteditable has some style, e.g through the // following CSS: // // strong { // color: red // } // // 2. A selection starts with the first character of a styled node and ends // outside of that node, e.g: "big beautiful" is selected in the following // html: // // <p contenteditable="true"> // Hello <strong>big</strong> beautiful world // </p> // // 3. The user types a letter character to replace "big beautiful", e.g. "x" // // Result: Webkits adds <font> and <b> tags: // // <p contenteditable="true"> // Hello // <font color="#ff0000"> // <b>f</b> // </font> // world // </p> // // This bug ONLY happens, if the first character of the node is selected and // the selection goes further than the node. // // Solution: // // Manually remove the element that would be removed anyway before inserting // the new letter. const rangyInstance = this.selectionWatcher.getFreshRange() if (!rangyInstance.isSelection) return const nodeToRemove = Keyboard.getNodeToRemove(rangyInstance.range, target) if (nodeToRemove) nodeToRemove.remove() } static getNodeToRemove (selectionRange, target) { // This function is only used by preventContenteditableBug. It is exposed on // the Keyboard constructor for testing purpose only. // Let's make sure we are in the edge-case, in which the bug happens. // The selection does not start at the beginning of a node. We have // nothing to do. if (selectionRange.startOffset !== 0) return let startNodeElement = selectionRange.startContainer // If the node is a textNode, we select its parent. if (startNodeElement.nodeType === nodeType.textNode) startNodeElement = startNodeElement.parentNode // The target is the contenteditable element, which we do not want to replace if (startNodeElement === target) return // We get a range that contains everything within the sartNodeElement to test // if the selectionRange is within the startNode, we have nothing to do. const startNodeRange = rangy.createRange() startNodeRange.setStartBefore(startNodeElement.firstChild) startNodeRange.setEndAfter(startNodeElement.lastChild) if (startNodeRange.containsRange(selectionRange)) return // If the selectionRange.startContainer was a textNode, we have to make sure // that its parent's content starts with this node. Content is either a // text node or an element. This is done to avoid false positives like the // following one: // <strong>foo<em>bar</em>|baz</strong>quux| if (selectionRange.startContainer.nodeType === nodeType.textNode) { const contentNodeTypes = [nodeType.textNode, nodeType.elementNode] let firstContentNode = startNodeElement.firstChild do { if (contentNodeTypes.indexOf(firstContentNode.nodeType) !== -1) break } while ((firstContentNode = firstContentNode.nextSibling)) if (firstContentNode !== selectionRange.startContainer) return } // Now we know, that we have to return at least the startNodeElement for // removal. But it could be, that we also need to remove its parent, e.g. // we need to remove <strong> in the following example: // <strong><em>|foo</em>bar</strong>baz| const rangeStartingBeforeCurrentElement = selectionRange.cloneRange() rangeStartingBeforeCurrentElement.setStartBefore(startNodeElement) return Keyboard.getNodeToRemove( rangeStartingBeforeCurrentElement, target ) || startNodeElement } }
JavaScript
class Ripple extends Component { onClick = e => { this.createRipple(e); }; createRipple = e => { const btnWidth = this.element.clientWidth; const rect = this.element.getBoundingClientRect(); const btnOffsetTop = rect.top; const btnOffsetLeft = rect.left; const posMouseX = e.pageX; const posMouseY = e.pageY; const rippleX = posMouseX - btnOffsetLeft; const rippleY = posMouseY - btnOffsetTop; const rippleAnimate = document.createElement('div'); rippleAnimate.className = 'ripple-animate'; const baseStyle = ` top: ${rippleY - btnWidth}px; left: ${rippleX - btnWidth}px; width: ${btnWidth * 2}px; height: ${btnWidth * 2}px; `; rippleAnimate.style.cssText = baseStyle; this.element.appendChild(rippleAnimate); setTimeout(() => { requestAnimationFrame(() => { rippleAnimate.style.cssText = `${baseStyle } transform: scale(1); -webkit-transition: scale(1); opacity: 0;`; }); }, 50); // If the delay is not added, the animation will not take effect, and the reason is not found. setTimeout(() => { rippleAnimate.remove(); }, 750); }; render() { const { children, type, ghost, ...otherProps } = this.props; return ( <a ref={node => { this.element = node }} className={cx('ripple-btn', type, { ghost })} {...otherProps} role="presentation" onClick={e => this.onClick(e)} > <span>{children}</span> </a> ); } }
JavaScript
class CustomLayoutExecutor extends LayoutExecutor { createMorphAnimation() { const graphMorphAnimation = super.createMorphAnimation() if (partitionGridVisualCreator) { // we want to animate the graph itself as well as the partition // grid visualization so we use a parallel animation: return IAnimation.createParallelAnimation([graphMorphAnimation, partitionGridVisualCreator]) } return graphMorphAnimation } }
JavaScript
class Mutable extends EventTarget { /** * Retrieves the type of this mutable subclass as the name of the runtime class * @returns The type of the mutable */ get type() { return this.constructor.name; } /** * Collect applicable attributes of the instance and copies of their values in a Mutator-object */ getMutator() { let mutator = {}; // collect primitive and mutable attributes for (let attribute in this) { let value = this[attribute]; if (value instanceof Function) continue; if (value instanceof Object && !(value instanceof Mutable)) continue; mutator[attribute] = this[attribute]; } // mutator can be reduced but not extended! Object.preventExtensions(mutator); // delete unwanted attributes this.reduceMutator(mutator); // replace references to mutable objects with references to copies for (let attribute in mutator) { let value = mutator[attribute]; if (value instanceof Mutable) mutator[attribute] = value.getMutator(); } return mutator; } /** * Collect the attributes of the instance and their values applicable for animation. * Basic functionality is identical to [[getMutator]], returned mutator should then be reduced by the subclassed instance */ getMutatorForAnimation() { return this.getMutator(); } /** * Collect the attributes of the instance and their values applicable for the user interface. * Basic functionality is identical to [[getMutator]], returned mutator should then be reduced by the subclassed instance */ getMutatorForUserInterface() { return this.getMutator(); } /** * Returns an associative array with the same attributes as the given mutator, but with the corresponding types as string-values * Does not recurse into objects! * @param _mutator */ getMutatorAttributeTypes(_mutator) { let types = {}; for (let attribute in _mutator) { let type = null; let value = _mutator[attribute]; if (_mutator[attribute] != undefined) if (typeof (value) == "object") type = this[attribute].constructor.name; else type = _mutator[attribute].constructor.name; types[attribute] = type; } return types; } /** * Updates the values of the given mutator according to the current state of the instance * @param _mutator */ updateMutator(_mutator) { for (let attribute in _mutator) { let value = _mutator[attribute]; if (value instanceof Mutable) value = value.getMutator(); else _mutator[attribute] = this[attribute]; } } /** * Updates the attribute values of the instance according to the state of the mutator. Must be protected...! * @param _mutator */ mutate(_mutator) { // TODO: don't assign unknown properties for (let attribute in _mutator) { let value = _mutator[attribute]; let mutant = this[attribute]; if (mutant instanceof Mutable) mutant.mutate(value); else this[attribute] = value; } this.dispatchEvent(new Event("mutate" /* MUTATE */)); } }
JavaScript
class Animation extends FudgeCore.Mutable { constructor(_name, _animStructure = {}, _fps = 60) { super(); this.totalTime = 0; this.labels = {}; this.stepsPerSecond = 10; this.events = {}; this.framesPerSecond = 60; // processed eventlist and animation strucutres for playback. this.eventsProcessed = new Map(); this.animationStructuresProcessed = new Map(); this.name = _name; this.animationStructure = _animStructure; this.animationStructuresProcessed.set(ANIMATION_STRUCTURE_TYPE.NORMAL, _animStructure); this.framesPerSecond = _fps; this.calculateTotalTime(); } /** * Generates a new "Mutator" with the information to apply to the [[Node]] the [[ComponentAnimator]] is attached to with [[Node.applyAnimation()]]. * @param _time The time at which the animation currently is at * @param _direction The direction in which the animation is supposed to be playing back. >0 == forward, 0 == stop, <0 == backwards * @param _playback The playbackmode the animation is supposed to be calculated with. * @returns a "Mutator" to apply. */ getMutated(_time, _direction, _playback) { let m = {}; if (_playback == FudgeCore.ANIMATION_PLAYBACK.TIMEBASED_CONTINOUS) { if (_direction >= 0) { m = this.traverseStructureForMutator(this.getProcessedAnimationStructure(ANIMATION_STRUCTURE_TYPE.NORMAL), _time); } else { m = this.traverseStructureForMutator(this.getProcessedAnimationStructure(ANIMATION_STRUCTURE_TYPE.REVERSE), _time); } } else { if (_direction >= 0) { m = this.traverseStructureForMutator(this.getProcessedAnimationStructure(ANIMATION_STRUCTURE_TYPE.RASTERED), _time); } else { m = this.traverseStructureForMutator(this.getProcessedAnimationStructure(ANIMATION_STRUCTURE_TYPE.RASTEREDREVERSE), _time); } } return m; } /** * Returns a list of the names of the events the [[ComponentAnimator]] needs to fire between _min and _max. * @param _min The minimum time (inclusive) to check between * @param _max The maximum time (exclusive) to check between * @param _playback The playback mode to check in. Has an effect on when the Events are fired. * @param _direction The direction the animation is supposed to run in. >0 == forward, 0 == stop, <0 == backwards * @returns a list of strings with the names of the custom events to fire. */ getEventsToFire(_min, _max, _playback, _direction) { let eventList = []; let minSection = Math.floor(_min / this.totalTime); let maxSection = Math.floor(_max / this.totalTime); _min = _min % this.totalTime; _max = _max % this.totalTime; while (minSection <= maxSection) { let eventTriggers = this.getCorrectEventList(_direction, _playback); if (minSection == maxSection) { eventList = eventList.concat(this.checkEventsBetween(eventTriggers, _min, _max)); } else { eventList = eventList.concat(this.checkEventsBetween(eventTriggers, _min, this.totalTime)); _min = 0; } minSection++; } return eventList; } /** * Adds an Event to the List of events. * @param _name The name of the event (needs to be unique per Animation). * @param _time The timestamp of the event (in milliseconds). */ setEvent(_name, _time) { this.events[_name] = _time; this.eventsProcessed.clear(); } /** * Removes the event with the given name from the list of events. * @param _name name of the event to remove. */ removeEvent(_name) { delete this.events[_name]; this.eventsProcessed.clear(); } get getLabels() { //TODO: this actually needs testing let en = new Enumerator(this.labels); return en; } get fps() { return this.framesPerSecond; } set fps(_fps) { this.framesPerSecond = _fps; this.eventsProcessed.clear(); this.animationStructuresProcessed.clear(); } /** * (Re-)Calculate the total time of the Animation. Calculation-heavy, use only if actually needed. */ calculateTotalTime() { this.totalTime = 0; this.traverseStructureForTime(this.animationStructure); } //#region transfer serialize() { let s = { idResource: this.idResource, name: this.name, labels: {}, events: {}, fps: this.framesPerSecond, sps: this.stepsPerSecond }; for (let name in this.labels) { s.labels[name] = this.labels[name]; } for (let name in this.events) { s.events[name] = this.events[name]; } s.animationStructure = this.traverseStructureForSerialisation(this.animationStructure); return s; } deserialize(_serialization) { this.idResource = _serialization.idResource; this.name = _serialization.name; this.framesPerSecond = _serialization.fps; this.stepsPerSecond = _serialization.sps; this.labels = {}; for (let name in _serialization.labels) { this.labels[name] = _serialization.labels[name]; } this.events = {}; for (let name in _serialization.events) { this.events[name] = _serialization.events[name]; } this.eventsProcessed = new Map(); this.animationStructure = this.traverseStructureForDeserialisation(_serialization.animationStructure); this.animationStructuresProcessed = new Map(); this.calculateTotalTime(); return this; } getMutator() { return this.serialize(); } reduceMutator(_mutator) { delete _mutator.totalTime; } /** * Traverses an AnimationStructure and returns the Serialization of said Structure. * @param _structure The Animation Structure at the current level to transform into the Serialization. * @returns the filled Serialization. */ traverseStructureForSerialisation(_structure) { let newSerialization = {}; for (let n in _structure) { if (_structure[n] instanceof FudgeCore.AnimationSequence) { newSerialization[n] = _structure[n].serialize(); } else { newSerialization[n] = this.traverseStructureForSerialisation(_structure[n]); } } return newSerialization; } /** * Traverses a Serialization to create a new AnimationStructure. * @param _serialization The serialization to transfer into an AnimationStructure * @returns the newly created AnimationStructure. */ traverseStructureForDeserialisation(_serialization) { let newStructure = {}; for (let n in _serialization) { if (_serialization[n].animationSequence) { let animSeq = new FudgeCore.AnimationSequence(); newStructure[n] = animSeq.deserialize(_serialization[n]); } else { newStructure[n] = this.traverseStructureForDeserialisation(_serialization[n]); } } return newStructure; } //#endregion /** * Finds the list of events to be used with these settings. * @param _direction The direction the animation is playing in. * @param _playback The playbackmode the animation is playing in. * @returns The correct AnimationEventTrigger Object to use */ getCorrectEventList(_direction, _playback) { if (_playback != FudgeCore.ANIMATION_PLAYBACK.FRAMEBASED) { if (_direction >= 0) { return this.getProcessedEventTrigger(ANIMATION_STRUCTURE_TYPE.NORMAL); } else { return this.getProcessedEventTrigger(ANIMATION_STRUCTURE_TYPE.REVERSE); } } else { if (_direction >= 0) { return this.getProcessedEventTrigger(ANIMATION_STRUCTURE_TYPE.RASTERED); } else { return this.getProcessedEventTrigger(ANIMATION_STRUCTURE_TYPE.RASTEREDREVERSE); } } } /** * Traverses an AnimationStructure to turn it into the "Mutator" to return to the Component. * @param _structure The strcuture to traverse * @param _time the point in time to write the animation numbers into. * @returns The "Mutator" filled with the correct values at the given time. */ traverseStructureForMutator(_structure, _time) { let newMutator = {}; for (let n in _structure) { if (_structure[n] instanceof FudgeCore.AnimationSequence) { newMutator[n] = _structure[n].evaluate(_time); } else { newMutator[n] = this.traverseStructureForMutator(_structure[n], _time); } } return newMutator; } /** * Traverses the current AnimationStrcuture to find the totalTime of this animation. * @param _structure The structure to traverse */ traverseStructureForTime(_structure) { for (let n in _structure) { if (_structure[n] instanceof FudgeCore.AnimationSequence) { let sequence = _structure[n]; if (sequence.length > 0) { let sequenceTime = sequence.getKey(sequence.length - 1).Time; this.totalTime = sequenceTime > this.totalTime ? sequenceTime : this.totalTime; } } else { this.traverseStructureForTime(_structure[n]); } } } /** * Ensures the existance of the requested [[AnimationStrcuture]] and returns it. * @param _type the type of the structure to get * @returns the requested [[AnimationStructure]] */ getProcessedAnimationStructure(_type) { if (!this.animationStructuresProcessed.has(_type)) { this.calculateTotalTime(); let ae = {}; switch (_type) { case ANIMATION_STRUCTURE_TYPE.NORMAL: ae = this.animationStructure; break; case ANIMATION_STRUCTURE_TYPE.REVERSE: ae = this.traverseStructureForNewStructure(this.animationStructure, this.calculateReverseSequence.bind(this)); break; case ANIMATION_STRUCTURE_TYPE.RASTERED: ae = this.traverseStructureForNewStructure(this.animationStructure, this.calculateRasteredSequence.bind(this)); break; case ANIMATION_STRUCTURE_TYPE.RASTEREDREVERSE: ae = this.traverseStructureForNewStructure(this.getProcessedAnimationStructure(ANIMATION_STRUCTURE_TYPE.REVERSE), this.calculateRasteredSequence.bind(this)); break; default: return {}; } this.animationStructuresProcessed.set(_type, ae); } return this.animationStructuresProcessed.get(_type); } /** * Ensures the existance of the requested [[AnimationEventTrigger]] and returns it. * @param _type The type of AnimationEventTrigger to get * @returns the requested [[AnimationEventTrigger]] */ getProcessedEventTrigger(_type) { if (!this.eventsProcessed.has(_type)) { this.calculateTotalTime(); let ev = {}; switch (_type) { case ANIMATION_STRUCTURE_TYPE.NORMAL: ev = this.events; break; case ANIMATION_STRUCTURE_TYPE.REVERSE: ev = this.calculateReverseEventTriggers(this.events); break; case ANIMATION_STRUCTURE_TYPE.RASTERED: ev = this.calculateRasteredEventTriggers(this.events); break; case ANIMATION_STRUCTURE_TYPE.RASTEREDREVERSE: ev = this.calculateRasteredEventTriggers(this.getProcessedEventTrigger(ANIMATION_STRUCTURE_TYPE.REVERSE)); break; default: return {}; } this.eventsProcessed.set(_type, ev); } return this.eventsProcessed.get(_type); } /** * Traverses an existing structure to apply a recalculation function to the AnimationStructure to store in a new Structure. * @param _oldStructure The old structure to traverse * @param _functionToUse The function to use to recalculated the structure. * @returns A new Animation Structure with the recalulated Animation Sequences. */ traverseStructureForNewStructure(_oldStructure, _functionToUse) { let newStructure = {}; for (let n in _oldStructure) { if (_oldStructure[n] instanceof FudgeCore.AnimationSequence) { newStructure[n] = _functionToUse(_oldStructure[n]); } else { newStructure[n] = this.traverseStructureForNewStructure(_oldStructure[n], _functionToUse); } } return newStructure; } /** * Creates a reversed Animation Sequence out of a given Sequence. * @param _sequence The sequence to calculate the new sequence out of * @returns The reversed Sequence */ calculateReverseSequence(_sequence) { let seq = new FudgeCore.AnimationSequence(); for (let i = 0; i < _sequence.length; i++) { let oldKey = _sequence.getKey(i); let key = new FudgeCore.AnimationKey(this.totalTime - oldKey.Time, oldKey.Value, oldKey.SlopeOut, oldKey.SlopeIn, oldKey.Constant); seq.addKey(key); } return seq; } /** * Creates a rastered [[AnimationSequence]] out of a given sequence. * @param _sequence The sequence to calculate the new sequence out of * @returns the rastered sequence. */ calculateRasteredSequence(_sequence) { let seq = new FudgeCore.AnimationSequence(); let frameTime = 1000 / this.framesPerSecond; for (let i = 0; i < this.totalTime; i += frameTime) { let key = new FudgeCore.AnimationKey(i, _sequence.evaluate(i), 0, 0, true); seq.addKey(key); } return seq; } /** * Creates a new reversed [[AnimationEventTrigger]] object based on the given one. * @param _events the event object to calculate the new one out of * @returns the reversed event object */ calculateReverseEventTriggers(_events) { let ae = {}; for (let name in _events) { ae[name] = this.totalTime - _events[name]; } return ae; } /** * Creates a rastered [[AnimationEventTrigger]] object based on the given one. * @param _events the event object to calculate the new one out of * @returns the rastered event object */ calculateRasteredEventTriggers(_events) { let ae = {}; let frameTime = 1000 / this.framesPerSecond; for (let name in _events) { ae[name] = _events[name] - (_events[name] % frameTime); } return ae; } /** * Checks which events lay between two given times and returns the names of the ones that do. * @param _eventTriggers The event object to check the events inside of * @param _min the minimum of the range to check between (inclusive) * @param _max the maximum of the range to check between (exclusive) * @returns an array of the names of the events in the given range. */ checkEventsBetween(_eventTriggers, _min, _max) { let eventsToTrigger = []; for (let name in _eventTriggers) { if (_min <= _eventTriggers[name] && _eventTriggers[name] < _max) { eventsToTrigger.push(name); } } return eventsToTrigger; } }
JavaScript
class AnimationKey extends FudgeCore.Mutable { constructor(_time = 0, _value = 0, _slopeIn = 0, _slopeOut = 0, _constant = false) { super(); this.constant = false; this.slopeIn = 0; this.slopeOut = 0; this.time = _time; this.value = _value; this.slopeIn = _slopeIn; this.slopeOut = _slopeOut; this.constant = _constant; this.broken = this.slopeIn != -this.slopeOut; this.functionOut = new FudgeCore.AnimationFunction(this, null); } get Time() { return this.time; } set Time(_time) { this.time = _time; this.functionIn.calculate(); this.functionOut.calculate(); } get Value() { return this.value; } set Value(_value) { this.value = _value; this.functionIn.calculate(); this.functionOut.calculate(); } get Constant() { return this.constant; } set Constant(_constant) { this.constant = _constant; this.functionIn.calculate(); this.functionOut.calculate(); } get SlopeIn() { return this.slopeIn; } set SlopeIn(_slope) { this.slopeIn = _slope; this.functionIn.calculate(); } get SlopeOut() { return this.slopeOut; } set SlopeOut(_slope) { this.slopeOut = _slope; this.functionOut.calculate(); } /** * Static comparation function to use in an array sort function to sort the keys by their time. * @param _a the animation key to check * @param _b the animation key to check against * @returns >0 if a>b, 0 if a=b, <0 if a<b */ static compare(_a, _b) { return _a.time - _b.time; } //#region transfer serialize() { let s = {}; s.time = this.time; s.value = this.value; s.slopeIn = this.slopeIn; s.slopeOut = this.slopeOut; s.constant = this.constant; return s; } deserialize(_serialization) { this.time = _serialization.time; this.value = _serialization.value; this.slopeIn = _serialization.slopeIn; this.slopeOut = _serialization.slopeOut; this.constant = _serialization.constant; this.broken = this.slopeIn != -this.slopeOut; return this; } getMutator() { return this.serialize(); } reduceMutator(_mutator) { // } }
JavaScript
class Audio { /** * Constructor for the [[Audio]] Class * @param _audioContext from [[AudioSettings]] * @param _gainValue 0 for muted | 1 for max volume */ constructor(_audioContext, _audioSessionData, _url, _gainValue, _loop) { this.init(_audioContext, _audioSessionData, _url, _gainValue, _loop); } async init(_audioContext, _audioSessionData, _url, _gainValue, _loop) { // Do everything in constructor // Add url to Audio this.url = _url; console.log("Audio url " + this.url); // Get AudioBuffer const bufferProm = _audioSessionData.urlToBuffer(_audioContext, _url); while (!bufferProm) { console.log("waiting..."); } await bufferProm.then(val => { this.audioBuffer = val; console.log("valBuffer " + val); }); console.log("Audio audiobuffer " + this.audioBuffer); // // Add local Gain for Audio and connect this.localGain = await _audioContext.createGain(); this.localGainValue = await _gainValue; //create Audio await this.createAudio(_audioContext, this.audioBuffer); } /** * initBufferSource */ initBufferSource(_audioContext) { this.bufferSource = _audioContext.createBufferSource(); this.bufferSource.buffer = this.audioBuffer; console.log("bS = " + this.bufferSource); this.bufferSource.connect(_audioContext.destination); this.setLoop(); this.addLocalGain(); console.log("BufferSource.buffer: " + this.bufferSource.buffer); console.log("AudioBuffer: " + this.audioBuffer); } //#region Getter/Setter LocalGainValue setLocalGainValue(_localGainValue) { this.localGainValue = _localGainValue; } getLocalGainValue() { return this.localGainValue; } //#endregion Getter/Setter LocalGainValue setBufferSource(_buffer) { this.bufferSource.buffer = _buffer; } /** * createAudio builds an [[Audio]] to use with the [[ComponentAudio]] * @param _audioContext from [[AudioSettings]] * @param _audioBuffer from [[AudioSessionData]] */ createAudio(_audioContext, _audioBuffer) { console.log("createAudio() " + " | " + " AudioContext: " + _audioContext); this.audioBuffer = _audioBuffer; console.log("aB = " + this.audioBuffer); // AudioBuffersourceNode Setup this.initBufferSource(_audioContext); return this.audioBuffer; } setLoop() { this.bufferSource.loop = this.isLooping; } addLocalGain() { this.bufferSource.connect(this.localGain); } }
JavaScript
class AudioListener { //##TODO AudioListener constructor(_audioContext) { //this.audioListener = _audioContext.listener; } /** * We will call setAudioListenerPosition whenever there is a need to change Positions. * All the position values should be identical to the current Position this is atteched to. */ // public setAudioListenerPosition(_position: Vector3): void { // this.audioListener.positionX.value = _position.x; // this.audioListener.positionY.value = _position.y; // this.audioListener.positionZ.value = _position.z; // this.position = _position; // } /** * getAudioListenerPosition */ getAudioListenerPosition() { return this.position; } /** * setAudioListenerOrientation */ // public setAudioListenerOrientation(_orientation: Vector3): void { // this.audioListener.orientationX.value = _orientation.x; // this.audioListener.orientationY.value = _orientation.y; // this.audioListener.orientationZ.value = _orientation.z; // this.orientation = _orientation; // } /** * getAudioListenerOrientation */ getAudioListenerOrientation() { return this.orientation; } }
JavaScript
class AudioSessionData { /** * constructor of the [[AudioSessionData]] class */ constructor() { this.dataArray = new Array(); this.bufferCounter = 0; } /** * getBufferCounter returns [bufferCounter] to keep track of number of different used sounds */ getBufferCounter() { return this.bufferCounter; } /** * Decoding Audio Data * Asynchronous Function to permit the loading of multiple Data Sources at the same time * @param _url URL as String for Data fetching */ async urlToBuffer(_audioContext, _url) { console.log("inside urlToBuffer"); let initObject = { method: "GET", mode: "same-origin", cache: "no-cache", headers: { "Content-Type": "audio/mpeg3" }, redirect: "follow" // default -> follow }; // Check for existing URL in DataArray, if no data inside add new AudioData //this.pushDataArray(_url, null); console.log("length" + this.dataArray.length); if (this.dataArray.length == 0) { try { // need window to fetch? const response = await window.fetch(_url, initObject); const arrayBuffer = await response.arrayBuffer(); const decodedAudio = await _audioContext.decodeAudioData(arrayBuffer); this.pushDataArray(_url, decodedAudio); //this.dataArray[this.dataArray.length].buffer = decodedAudio; console.log("length " + this.dataArray.length); return decodedAudio; } catch (e) { this.logErrorFetch(e); return null; } } else { // If needed URL is inside Array, // iterate through all existing Data to get needed values for (let x = 0; x < this.dataArray.length; x++) { console.log("what is happening"); if (this.dataArray[x].url == _url) { console.log("found existing url"); return this.dataArray[x].buffer; } } return null; } } /** * pushTuple Source and Decoded Audio Data gets saved for later use * @param _url URL from used Data * @param _audioBuffer AudioBuffer generated from URL */ pushDataArray(_url, _audioBuffer) { let data; data = { url: _url, buffer: _audioBuffer, counter: this.bufferCounter }; this.dataArray.push(data); console.log("array: " + this.dataArray); //TODO audioBufferHolder obsolete if array working this.setAudioBufferHolder(data); console.log("dataPair " + data.url + " " + data.buffer + " " + data.counter); this.bufferCounter += 1; return this.audioBufferHolder; } /** * iterateArray * Look at saved Data Count */ countDataInArray() { console.log("DataArray Length: " + this.dataArray.length); } /** * showDataInArray * Show all Data in Array */ showDataInArray() { for (let x = 0; x < this.dataArray.length; x++) { console.log("Array Data: " + this.dataArray[x].url + this.dataArray[x].buffer); } } /** * getAudioBuffer */ getAudioBufferHolder() { return this.audioBufferHolder; } /** * setAudioBuffer */ setAudioBufferHolder(_audioData) { this.audioBufferHolder = _audioData; } /** * Error Message for Data Fetching * @param e Error */ logErrorFetch(e) { console.log("Audio error", e); } }
JavaScript
class AudioSettings { // /** * Constructor for master Volume * @param _gainValue */ constructor(_gainValue) { this.setAudioContext(new AudioContext({ latencyHint: "interactive", sampleRate: 44100 })); //this.globalAudioContext.resume(); console.log("GlobalAudioContext: " + this.globalAudioContext); this.masterGain = this.globalAudioContext.createGain(); this.masterGainValue = _gainValue; //this.audioSessionData = new AudioSessionData(); } setMasterGainValue(_masterGainValue) { this.masterGainValue = _masterGainValue; } getMasterGainValue() { return this.masterGainValue; } getAudioContext() { return this.globalAudioContext; } setAudioContext(_audioContext) { this.globalAudioContext = _audioContext; } }
JavaScript
class RenderOperator { /** * Checks the first parameter and throws an exception with the WebGL-errorcode if the value is null * @param _value // value to check against null * @param _message // optional, additional message for the exception */ static assert(_value, _message = "") { if (_value === null) throw new Error(`Assertion failed. ${_message}, WebGL-Error: ${RenderOperator.crc3 ? RenderOperator.crc3.getError() : ""}`); return _value; } /** * Initializes offscreen-canvas, renderingcontext and hardware viewport. */ static initialize(_antialias = false, _alpha = false) { let contextAttributes = { alpha: _alpha, antialias: _antialias }; let canvas = document.createElement("canvas"); RenderOperator.crc3 = RenderOperator.assert(canvas.getContext("webgl2", contextAttributes), "WebGL-context couldn't be created"); // Enable backface- and zBuffer-culling. RenderOperator.crc3.enable(WebGL2RenderingContext.CULL_FACE); RenderOperator.crc3.enable(WebGL2RenderingContext.DEPTH_TEST); // RenderOperator.crc3.pixelStorei(WebGL2RenderingContext.UNPACK_FLIP_Y_WEBGL, true); RenderOperator.rectViewport = RenderOperator.getCanvasRect(); RenderOperator.renderShaderRayCast = RenderOperator.createProgram(FudgeCore.ShaderRayCast); } /** * Return a reference to the offscreen-canvas */ static getCanvas() { return RenderOperator.crc3.canvas; // TODO: enable OffscreenCanvas } /** * Return a reference to the rendering context */ static getRenderingContext() { return RenderOperator.crc3; } /** * Return a rectangle describing the size of the offscreen-canvas. x,y are 0 at all times. */ static getCanvasRect() { let canvas = RenderOperator.crc3.canvas; return FudgeCore.Rectangle.GET(0, 0, canvas.width, canvas.height); } /** * Set the size of the offscreen-canvas. */ static setCanvasSize(_width, _height) { RenderOperator.crc3.canvas.width = _width; RenderOperator.crc3.canvas.height = _height; } /** * Set the area on the offscreen-canvas to render the camera image to. * @param _rect */ static setViewportRectangle(_rect) { Object.assign(RenderOperator.rectViewport, _rect); RenderOperator.crc3.viewport(_rect.x, _rect.y, _rect.width, _rect.height); } /** * Retrieve the area on the offscreen-canvas the camera image gets rendered to. */ static getViewportRectangle() { return RenderOperator.rectViewport; } /** * Convert light data to flat arrays * TODO: this method appears to be obsolete...? */ static createRenderLights(_lights) { let renderLights = {}; for (let entry of _lights) { // TODO: simplyfy, since direction is now handled by ComponentLight switch (entry[0]) { case FudgeCore.LightAmbient.name: let ambient = []; for (let cmpLight of entry[1]) { let c = cmpLight.light.color; ambient.push(c.r, c.g, c.b, c.a); } renderLights["u_ambient"] = new Float32Array(ambient); break; case FudgeCore.LightDirectional.name: let directional = []; for (let cmpLight of entry[1]) { let c = cmpLight.light.color; // let d: Vector3 = (<LightDirectional>light.getLight()).direction; directional.push(c.r, c.g, c.b, c.a, 0, 0, 1); } renderLights["u_directional"] = new Float32Array(directional); break; default: FudgeCore.Debug.warn("Shaderstructure undefined for", entry[0]); } } return renderLights; } /** * Set light data in shaders */ static setLightsInShader(_renderShader, _lights) { RenderOperator.useProgram(_renderShader); let uni = _renderShader.uniforms; let ambient = uni["u_ambient.color"]; if (ambient) { let cmpLights = _lights.get("LightAmbient"); if (cmpLights) { // TODO: add up ambient lights to a single color // let result: Color = new Color(0, 0, 0, 1); for (let cmpLight of cmpLights) // for now, only the last is relevant RenderOperator.crc3.uniform4fv(ambient, cmpLight.light.color.getArray()); } } let nDirectional = uni["u_nLightsDirectional"]; if (nDirectional) { let cmpLights = _lights.get("LightDirectional"); if (cmpLights) { let n = cmpLights.length; RenderOperator.crc3.uniform1ui(nDirectional, n); for (let i = 0; i < n; i++) { let cmpLight = cmpLights[i]; RenderOperator.crc3.uniform4fv(uni[`u_directional[${i}].color`], cmpLight.light.color.getArray()); let direction = FudgeCore.Vector3.Z(); direction.transform(cmpLight.pivot); direction.transform(cmpLight.getContainer().mtxWorld); RenderOperator.crc3.uniform3fv(uni[`u_directional[${i}].direction`], direction.get()); } } } // debugger; } /** * Draw a mesh buffer using the given infos and the complete projection matrix * @param _renderShader * @param _renderBuffers * @param _renderCoat * @param _world * @param _projection */ static draw(_renderShader, _renderBuffers, _renderCoat, _world, _projection) { RenderOperator.useProgram(_renderShader); // RenderOperator.useBuffers(_renderBuffers); // RenderOperator.useParameter(_renderCoat); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, _renderBuffers.vertices); RenderOperator.crc3.enableVertexAttribArray(_renderShader.attributes["a_position"]); RenderOperator.setAttributeStructure(_renderShader.attributes["a_position"], FudgeCore.Mesh.getBufferSpecification()); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER, _renderBuffers.indices); if (_renderShader.attributes["a_textureUVs"]) { RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, _renderBuffers.textureUVs); RenderOperator.crc3.enableVertexAttribArray(_renderShader.attributes["a_textureUVs"]); // enable the buffer RenderOperator.crc3.vertexAttribPointer(_renderShader.attributes["a_textureUVs"], 2, WebGL2RenderingContext.FLOAT, false, 0, 0); } // Supply matrixdata to shader. let uProjection = _renderShader.uniforms["u_projection"]; RenderOperator.crc3.uniformMatrix4fv(uProjection, false, _projection.get()); if (_renderShader.uniforms["u_world"]) { let uWorld = _renderShader.uniforms["u_world"]; RenderOperator.crc3.uniformMatrix4fv(uWorld, false, _world.get()); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, _renderBuffers.normalsFace); RenderOperator.crc3.enableVertexAttribArray(_renderShader.attributes["a_normal"]); RenderOperator.setAttributeStructure(_renderShader.attributes["a_normal"], FudgeCore.Mesh.getBufferSpecification()); } // TODO: this is all that's left of coat handling in RenderOperator, due to injection. So extra reference from node to coat is unnecessary _renderCoat.coat.useRenderData(_renderShader); // Draw call // RenderOperator.crc3.drawElements(WebGL2RenderingContext.TRIANGLES, Mesh.getBufferSpecification().offset, _renderBuffers.nIndices); RenderOperator.crc3.drawElements(WebGL2RenderingContext.TRIANGLES, _renderBuffers.nIndices, WebGL2RenderingContext.UNSIGNED_SHORT, 0); } /** * Draw a buffer with a special shader that uses an id instead of a color * @param _renderShader * @param _renderBuffers * @param _world * @param _projection */ static drawForRayCast(_id, _renderBuffers, _world, _projection) { let renderShader = RenderOperator.renderShaderRayCast; RenderOperator.useProgram(renderShader); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, _renderBuffers.vertices); RenderOperator.crc3.enableVertexAttribArray(renderShader.attributes["a_position"]); RenderOperator.setAttributeStructure(renderShader.attributes["a_position"], FudgeCore.Mesh.getBufferSpecification()); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER, _renderBuffers.indices); // Supply matrixdata to shader. let uProjection = renderShader.uniforms["u_projection"]; RenderOperator.crc3.uniformMatrix4fv(uProjection, false, _projection.get()); if (renderShader.uniforms["u_world"]) { let uWorld = renderShader.uniforms["u_world"]; RenderOperator.crc3.uniformMatrix4fv(uWorld, false, _world.get()); } let idUniformLocation = renderShader.uniforms["u_id"]; RenderOperator.getRenderingContext().uniform1i(idUniformLocation, _id); RenderOperator.crc3.drawElements(WebGL2RenderingContext.TRIANGLES, _renderBuffers.nIndices, WebGL2RenderingContext.UNSIGNED_SHORT, 0); } // #region Shaderprogram static createProgram(_shaderClass) { let crc3 = RenderOperator.crc3; let program = crc3.createProgram(); let renderShader; try { crc3.attachShader(program, RenderOperator.assert(compileShader(_shaderClass.getVertexShaderSource(), WebGL2RenderingContext.VERTEX_SHADER))); crc3.attachShader(program, RenderOperator.assert(compileShader(_shaderClass.getFragmentShaderSource(), WebGL2RenderingContext.FRAGMENT_SHADER))); crc3.linkProgram(program); let error = RenderOperator.assert(crc3.getProgramInfoLog(program)); if (error !== "") { throw new Error("Error linking Shader: " + error); } renderShader = { program: program, attributes: detectAttributes(), uniforms: detectUniforms() }; } catch (_error) { FudgeCore.Debug.error(_error); debugger; } return renderShader; function compileShader(_shaderCode, _shaderType) { let webGLShader = crc3.createShader(_shaderType); crc3.shaderSource(webGLShader, _shaderCode); crc3.compileShader(webGLShader); let error = RenderOperator.assert(crc3.getShaderInfoLog(webGLShader)); if (error !== "") { throw new Error("Error compiling shader: " + error); } // Check for any compilation errors. if (!crc3.getShaderParameter(webGLShader, WebGL2RenderingContext.COMPILE_STATUS)) { alert(crc3.getShaderInfoLog(webGLShader)); return null; } return webGLShader; } function detectAttributes() { let detectedAttributes = {}; let attributeCount = crc3.getProgramParameter(program, WebGL2RenderingContext.ACTIVE_ATTRIBUTES); for (let i = 0; i < attributeCount; i++) { let attributeInfo = RenderOperator.assert(crc3.getActiveAttrib(program, i)); if (!attributeInfo) { break; } detectedAttributes[attributeInfo.name] = crc3.getAttribLocation(program, attributeInfo.name); } return detectedAttributes; } function detectUniforms() { let detectedUniforms = {}; let uniformCount = crc3.getProgramParameter(program, WebGL2RenderingContext.ACTIVE_UNIFORMS); for (let i = 0; i < uniformCount; i++) { let info = RenderOperator.assert(crc3.getActiveUniform(program, i)); if (!info) { break; } detectedUniforms[info.name] = RenderOperator.assert(crc3.getUniformLocation(program, info.name)); } return detectedUniforms; } } static useProgram(_shaderInfo) { RenderOperator.crc3.useProgram(_shaderInfo.program); RenderOperator.crc3.enableVertexAttribArray(_shaderInfo.attributes["a_position"]); } static deleteProgram(_program) { if (_program) { RenderOperator.crc3.deleteProgram(_program.program); delete _program.attributes; delete _program.uniforms; } } // #endregion // #region Meshbuffer static createBuffers(_mesh) { let vertices = RenderOperator.assert(RenderOperator.crc3.createBuffer()); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, vertices); RenderOperator.crc3.bufferData(WebGL2RenderingContext.ARRAY_BUFFER, _mesh.vertices, WebGL2RenderingContext.STATIC_DRAW); let indices = RenderOperator.assert(RenderOperator.crc3.createBuffer()); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER, indices); RenderOperator.crc3.bufferData(WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER, _mesh.indices, WebGL2RenderingContext.STATIC_DRAW); let textureUVs = RenderOperator.crc3.createBuffer(); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, textureUVs); RenderOperator.crc3.bufferData(WebGL2RenderingContext.ARRAY_BUFFER, _mesh.textureUVs, WebGL2RenderingContext.STATIC_DRAW); let normalsFace = RenderOperator.assert(RenderOperator.crc3.createBuffer()); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, normalsFace); RenderOperator.crc3.bufferData(WebGL2RenderingContext.ARRAY_BUFFER, _mesh.normalsFace, WebGL2RenderingContext.STATIC_DRAW); let bufferInfo = { vertices: vertices, indices: indices, nIndices: _mesh.getIndexCount(), textureUVs: textureUVs, normalsFace: normalsFace }; return bufferInfo; } static useBuffers(_renderBuffers) { // TODO: currently unused, done specifically in draw. Could be saved in VAO within RenderBuffers // RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, _renderBuffers.vertices); // RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER, _renderBuffers.indices); // RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, _renderBuffers.textureUVs); } static deleteBuffers(_renderBuffers) { if (_renderBuffers) { RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ARRAY_BUFFER, null); RenderOperator.crc3.deleteBuffer(_renderBuffers.vertices); RenderOperator.crc3.deleteBuffer(_renderBuffers.textureUVs); RenderOperator.crc3.bindBuffer(WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER, null); RenderOperator.crc3.deleteBuffer(_renderBuffers.indices); } } // #endregion // #region MaterialParameters static createParameter(_coat) { // let vao: WebGLVertexArrayObject = RenderOperator.assert<WebGLVertexArrayObject>(RenderOperator.crc3.createVertexArray()); let coatInfo = { //vao: null, coat: _coat }; return coatInfo; } static useParameter(_coatInfo) { // RenderOperator.crc3.bindVertexArray(_coatInfo.vao); } static deleteParameter(_coatInfo) { if (_coatInfo) { RenderOperator.crc3.bindVertexArray(null); // RenderOperator.crc3.deleteVertexArray(_coatInfo.vao); } } // #endregion /** * Wrapper function to utilize the bufferSpecification interface when passing data to the shader via a buffer. * @param _attributeLocation // The location of the attribute on the shader, to which they data will be passed. * @param _bufferSpecification // Interface passing datapullspecifications to the buffer. */ static setAttributeStructure(_attributeLocation, _bufferSpecification) { RenderOperator.crc3.vertexAttribPointer(_attributeLocation, _bufferSpecification.size, _bufferSpecification.dataType, _bufferSpecification.normalize, _bufferSpecification.stride, _bufferSpecification.offset); } }
JavaScript
class Coat extends FudgeCore.Mutable { constructor() { super(...arguments); this.name = "Coat"; //#endregion } mutate(_mutator) { super.mutate(_mutator); } useRenderData(_renderShader) { } //#region Transfer serialize() { let serialization = this.getMutator(); return serialization; } deserialize(_serialization) { this.mutate(_serialization); return this; } reduceMutator() { } }
JavaScript
class ComponentAnimator extends FudgeCore.Component { constructor(_animation = new FudgeCore.Animation(""), _playmode = ANIMATION_PLAYMODE.LOOP, _playback = ANIMATION_PLAYBACK.TIMEBASED_CONTINOUS) { super(); this.speedScalesWithGlobalSpeed = true; this.speedScale = 1; this.lastTime = 0; this.animation = _animation; this.playmode = _playmode; this.playback = _playback; this.localTime = new FudgeCore.Time(); //TODO: update animation total time when loading a different animation? this.animation.calculateTotalTime(); FudgeCore.Loop.addEventListener("loopFrame" /* LOOP_FRAME */, this.updateAnimationLoop.bind(this)); FudgeCore.Time.game.addEventListener("timeScaled" /* TIME_SCALED */, this.updateScale.bind(this)); } set speed(_s) { this.speedScale = _s; this.updateScale(); } /** * Jumps to a certain time in the animation to play from there. * @param _time The time to jump to */ jumpTo(_time) { this.localTime.set(_time); this.lastTime = _time; _time = _time % this.animation.totalTime; let mutator = this.animation.getMutated(_time, this.calculateDirection(_time), this.playback); this.getContainer().applyAnimation(mutator); } /** * Returns the current time of the animation, modulated for animation length. */ getCurrentTime() { return this.localTime.get() % this.animation.totalTime; } /** * Forces an update of the animation from outside. Used in the ViewAnimation. Shouldn't be used during the game. * @param _time the (unscaled) time to update the animation with. * @returns a Tupel containing the Mutator for Animation and the playmode corrected time. */ updateAnimation(_time) { return this.updateAnimationLoop(null, _time); } //#region transfer serialize() { let s = super.serialize(); s["animation"] = this.animation.serialize(); s["playmode"] = this.playmode; s["playback"] = this.playback; s["speedScale"] = this.speedScale; s["speedScalesWithGlobalSpeed"] = this.speedScalesWithGlobalSpeed; s[super.constructor.name] = super.serialize(); return s; } deserialize(_s) { this.animation = new FudgeCore.Animation(""); this.animation.deserialize(_s.animation); this.playback = _s.playback; this.playmode = _s.playmode; this.speedScale = _s.speedScale; this.speedScalesWithGlobalSpeed = _s.speedScalesWithGlobalSpeed; super.deserialize(_s[super.constructor.name]); return this; } //#endregion //#region updateAnimation /** * Updates the Animation. * Gets called every time the Loop fires the LOOP_FRAME Event. * Uses the built-in time unless a different time is specified. * May also be called from updateAnimation(). */ updateAnimationLoop(_e, _time) { if (this.animation.totalTime == 0) return [null, 0]; let time = _time || this.localTime.get(); if (this.playback == ANIMATION_PLAYBACK.FRAMEBASED) { time = this.lastTime + (1000 / this.animation.fps); } let direction = this.calculateDirection(time); time = this.applyPlaymodes(time); this.executeEvents(this.animation.getEventsToFire(this.lastTime, time, this.playback, direction)); if (this.lastTime != time) { this.lastTime = time; time = time % this.animation.totalTime; let mutator = this.animation.getMutated(time, direction, this.playback); if (this.getContainer()) { this.getContainer().applyAnimation(mutator); } return [mutator, time]; } return [null, time]; } /** * Fires all custom events the Animation should have fired between the last frame and the current frame. * @param events a list of names of custom events to fire */ executeEvents(events) { for (let i = 0; i < events.length; i++) { this.dispatchEvent(new Event(events[i])); } } /** * Calculates the actual time to use, using the current playmodes. * @param _time the time to apply the playmodes to * @returns the recalculated time */ applyPlaymodes(_time) { switch (this.playmode) { case ANIMATION_PLAYMODE.STOP: return this.localTime.getOffset(); case ANIMATION_PLAYMODE.PLAYONCE: if (_time >= this.animation.totalTime) return this.animation.totalTime - 0.01; //TODO: this might cause some issues else return _time; case ANIMATION_PLAYMODE.PLAYONCESTOPAFTER: if (_time >= this.animation.totalTime) return this.animation.totalTime + 0.01; //TODO: this might cause some issues else return _time; default: return _time; } } /** * Calculates and returns the direction the animation should currently be playing in. * @param _time the time at which to calculate the direction * @returns 1 if forward, 0 if stop, -1 if backwards */ calculateDirection(_time) { switch (this.playmode) { case ANIMATION_PLAYMODE.STOP: return 0; // case ANIMATION_PLAYMODE.PINGPONG: // if (Math.floor(_time / this.animation.totalTime) % 2 == 0) // return 1; // else // return -1; case ANIMATION_PLAYMODE.REVERSELOOP: return -1; case ANIMATION_PLAYMODE.PLAYONCE: case ANIMATION_PLAYMODE.PLAYONCESTOPAFTER: if (_time >= this.animation.totalTime) { return 0; } default: return 1; } } /** * Updates the scale of the animation if the user changes it or if the global game timer changed its scale. */ updateScale() { let newScale = this.speedScale; if (this.speedScalesWithGlobalSpeed) newScale *= FudgeCore.Time.game.getScale(); this.localTime.setScale(newScale); } }
JavaScript
class ComponentAudio extends FudgeCore.Component { constructor(_audio) { super(); this.setAudio(_audio); } setLocalisation(_localisation) { this.localisation = _localisation; } /** * playAudio */ playAudio(_audioContext) { this.audio.initBufferSource(_audioContext); this.audio.bufferSource.start(_audioContext.currentTime); } /** * Adds an [[Audio]] to the [[ComponentAudio]] * @param _audio Decoded Audio Data as [[Audio]] */ setAudio(_audio) { this.audio = _audio; } }
JavaScript
class Light extends FudgeCore.Mutable { constructor(_color = new FudgeCore.Color(1, 1, 1, 1)) { super(); this.color = _color; } reduceMutator() { } }
JavaScript
class ComponentMaterial extends FudgeCore.Component { constructor(_material = null) { super(); this.material = _material; } //#region Transfer serialize() { let serialization; /* at this point of time, serialization as resource and as inline object is possible. TODO: check if inline becomes obsolete */ let idMaterial = this.material.idResource; if (idMaterial) serialization = { idMaterial: idMaterial }; else serialization = { material: FudgeCore.Serializer.serialize(this.material) }; serialization[super.constructor.name] = super.serialize(); return serialization; } deserialize(_serialization) { let material; if (_serialization.idMaterial) material = FudgeCore.ResourceManager.get(_serialization.idMaterial); else material = FudgeCore.Serializer.deserialize(_serialization.material); this.material = material; super.deserialize(_serialization[super.constructor.name]); return this; } }
JavaScript
class ComponentMesh extends FudgeCore.Component { constructor(_mesh = null) { super(); this.pivot = FudgeCore.Matrix4x4.IDENTITY; this.mesh = null; this.mesh = _mesh; } //#region Transfer serialize() { let serialization; /* at this point of time, serialization as resource and as inline object is possible. TODO: check if inline becomes obsolete */ let idMesh = this.mesh.idResource; if (idMesh) serialization = { idMesh: idMesh }; else serialization = { mesh: FudgeCore.Serializer.serialize(this.mesh) }; serialization.pivot = this.pivot.serialize(); serialization[super.constructor.name] = super.serialize(); return serialization; } deserialize(_serialization) { let mesh; if (_serialization.idMesh) mesh = FudgeCore.ResourceManager.get(_serialization.idMesh); else mesh = FudgeCore.Serializer.deserialize(_serialization.mesh); this.mesh = mesh; this.pivot.deserialize(_serialization.pivot); super.deserialize(_serialization[super.constructor.name]); return this; } }
JavaScript
class ComponentScript extends FudgeCore.Component { constructor() { super(); this.singleton = false; } serialize() { return this.getMutator(); } deserialize(_serialization) { this.mutate(_serialization); return this; } }
JavaScript
class ComponentTransform extends FudgeCore.Component { constructor(_matrix = FudgeCore.Matrix4x4.IDENTITY) { super(); this.local = _matrix; } //#region Transfer serialize() { let serialization = { local: this.local.serialize(), [super.constructor.name]: super.serialize() }; return serialization; } deserialize(_serialization) { super.deserialize(_serialization[super.constructor.name]); this.local.deserialize(_serialization.local); return this; } // public mutate(_mutator: Mutator): void { // this.local.mutate(_mutator); // } // public getMutator(): Mutator { // return this.local.getMutator(); // } // public getMutatorAttributeTypes(_mutator: Mutator): MutatorAttributeTypes { // let types: MutatorAttributeTypes = this.local.getMutatorAttributeTypes(_mutator); // return types; // } reduceMutator(_mutator) { delete _mutator.world; super.reduceMutator(_mutator); } }
JavaScript
class DebugTarget { static mergeArguments(_message, ..._args) { let out = JSON.stringify(_message); for (let arg of _args) out += "\n" + JSON.stringify(arg, null, 2); return out; } }
JavaScript
class DebugAlert extends FudgeCore.DebugTarget { static createDelegate(_headline) { let delegate = function (_message, ..._args) { let out = _headline + "\n\n" + FudgeCore.DebugTarget.mergeArguments(_message, ..._args); alert(out); }; return delegate; } }
JavaScript
class Debug { /** * De- / Activate a filter for the given DebugTarget. * @param _target * @param _filter */ static setFilter(_target, _filter) { for (let filter in Debug.delegates) Debug.delegates[filter].delete(_target); for (let filter in FudgeCore.DEBUG_FILTER) { let parsed = parseInt(filter); if (parsed == FudgeCore.DEBUG_FILTER.ALL) break; if (_filter & parsed) Debug.delegates[parsed].set(_target, _target.delegates[parsed]); } } /** * Debug function to be implemented by the DebugTarget. * info(...) displays additional information with low priority * @param _message * @param _args */ static info(_message, ..._args) { Debug.delegate(FudgeCore.DEBUG_FILTER.INFO, _message, _args); } /** * Debug function to be implemented by the DebugTarget. * log(...) displays information with medium priority * @param _message * @param _args */ static log(_message, ..._args) { Debug.delegate(FudgeCore.DEBUG_FILTER.LOG, _message, _args); } /** * Debug function to be implemented by the DebugTarget. * warn(...) displays information about non-conformities in usage, which is emphasized e.g. by color * @param _message * @param _args */ static warn(_message, ..._args) { Debug.delegate(FudgeCore.DEBUG_FILTER.WARN, _message, _args); } /** * Debug function to be implemented by the DebugTarget. * error(...) displays critical information about failures, which is emphasized e.g. by color * @param _message * @param _args */ static error(_message, ..._args) { Debug.delegate(FudgeCore.DEBUG_FILTER.ERROR, _message, _args); } /** * Lookup all delegates registered to the filter and call them using the given arguments * @param _filter * @param _message * @param _args */ static delegate(_filter, _message, _args) { let delegates = Debug.delegates[_filter]; for (let delegate of delegates.values()) if (_args.length > 0) delegate(_message, ..._args); else delegate(_message); } }
JavaScript
class DebugTextArea extends FudgeCore.DebugTarget { static createDelegate(_headline) { let delegate = function (_message, ..._args) { let out = _headline + "\n\n" + FudgeCore.DebugTarget.mergeArguments(_message, _args); DebugTextArea.textArea.textContent += out; }; return delegate; } }
JavaScript
class Color extends FudgeCore.Mutable { constructor(_r = 1, _g = 1, _b = 1, _a = 1) { super(); this.setNormRGBA(_r, _g, _b, _a); } static get BLACK() { return new Color(0, 0, 0, 1); } static get WHITE() { return new Color(1, 1, 1, 1); } static get RED() { return new Color(1, 0, 0, 1); } static get GREEN() { return new Color(0, 1, 0, 1); } static get BLUE() { return new Color(0, 0, 1, 1); } static get YELLOW() { return new Color(1, 1, 0, 1); } static get CYAN() { return new Color(0, 1, 1, 1); } static get MAGENTA() { return new Color(1, 0, 1, 1); } setNormRGBA(_r, _g, _b, _a) { this.r = Math.min(1, Math.max(0, _r)); this.g = Math.min(1, Math.max(0, _g)); this.b = Math.min(1, Math.max(0, _b)); this.a = Math.min(1, Math.max(0, _a)); } setBytesRGBA(_r, _g, _b, _a) { this.setNormRGBA(_r / 255, _g / 255, _b / 255, _a / 255); } getArray() { return new Float32Array([this.r, this.g, this.b, this.a]); } setArrayNormRGBA(_color) { this.setNormRGBA(_color[0], _color[1], _color[2], _color[3]); } setArrayBytesRGBA(_color) { this.setBytesRGBA(_color[0], _color[1], _color[2], _color[3]); } reduceMutator(_mutator) { } }
JavaScript
class Material { constructor(_name, _shader, _coat) { this.idResource = undefined; this.name = _name; this.shaderType = _shader; if (_shader) { if (_coat) this.setCoat(_coat); else this.setCoat(this.createCoatMatchingShader()); } } /** * Creates a new [[Coat]] instance that is valid for the [[Shader]] referenced by this material */ createCoatMatchingShader() { let coat = new (this.shaderType.getCoat())(); return coat; } /** * Makes this material reference the given [[Coat]] if it is compatible with the referenced [[Shader]] * @param _coat */ setCoat(_coat) { if (_coat.constructor != this.shaderType.getCoat()) throw (new Error("Shader and coat don't match")); this.coat = _coat; } /** * Returns the currently referenced [[Coat]] instance */ getCoat() { return this.coat; } /** * Changes the materials reference to the given [[Shader]], creates and references a new [[Coat]] instance * and mutates the new coat to preserve matching properties. * @param _shaderType */ setShader(_shaderType) { this.shaderType = _shaderType; let coat = this.createCoatMatchingShader(); coat.mutate(this.coat.getMutator()); this.setCoat(coat); } /** * Returns the [[Shader]] referenced by this material */ getShader() { return this.shaderType; } //#region Transfer // TODO: this type of serialization was implemented for implicit Material create. Check if obsolete when only one material class exists and/or materials are stored separately serialize() { let serialization = { name: this.name, idResource: this.idResource, shader: this.shaderType.name, coat: FudgeCore.Serializer.serialize(this.coat) }; return serialization; } deserialize(_serialization) { this.name = _serialization.name; this.idResource = _serialization.idResource; // TODO: provide for shaders in the users namespace. See Serializer fullpath etc. // tslint:disable-next-line: no-any this.shaderType = FudgeCore[_serialization.shader]; let coat = FudgeCore.Serializer.deserialize(_serialization.coat); this.setCoat(coat); return this; } }
JavaScript
class Recycler { /** * Returns an object of the requested type from the depot, or a new one, if the depot was empty * @param _T The class identifier of the desired object */ static get(_T) { let key = _T.name; let instances = Recycler.depot[key]; if (instances && instances.length > 0) return instances.pop(); else return new _T(); } /** * Stores the object in the depot for later recycling. Users are responsible for throwing in objects that are about to loose scope and are not referenced by any other * @param _instance */ static store(_instance) { let key = _instance.constructor.name; //Debug.log(key); let instances = Recycler.depot[key] || []; instances.push(_instance); Recycler.depot[key] = instances; // Debug.log(`ObjectManager.depot[${key}]: ${ObjectManager.depot[key].length}`); //Debug.log(this.depot); } /** * Emptys the depot of a given type, leaving the objects for the garbage collector. May result in a short stall when many objects were in * @param _T */ static dump(_T) { let key = _T.name; Recycler.depot[key] = []; } /** * Emptys all depots, leaving all objects to the garbage collector. May result in a short stall when many objects were in */ static dumpAll() { Recycler.depot = {}; } }
JavaScript
class ResourceManager { /** * Generates an id for the resources and registers it with the list of resources * @param _resource */ static register(_resource) { if (!_resource.idResource) _resource.idResource = ResourceManager.generateId(_resource); ResourceManager.resources[_resource.idResource] = _resource; } /** * Generate a user readable and unique id using the type of the resource, the date and random numbers * @param _resource */ static generateId(_resource) { // TODO: build id and integrate info from resource, not just date let idResource; do idResource = _resource.constructor.name + "|" + new Date().toISOString() + "|" + Math.random().toPrecision(5).substr(2, 5); while (ResourceManager.resources[idResource]); return idResource; } /** * Tests, if an object is a [[SerializableResource]] * @param _object The object to examine */ static isResource(_object) { return (Reflect.has(_object, "idResource")); } /** * Retrieves the resource stored with the given id * @param _idResource */ static get(_idResource) { let resource = ResourceManager.resources[_idResource]; if (!resource) { let serialization = ResourceManager.serialization[_idResource]; if (!serialization) { FudgeCore.Debug.error("Resource not found", _idResource); return null; } resource = ResourceManager.deserializeResource(serialization); } return resource; } /** * Creates and registers a resource from a [[Node]], copying the complete branch starting with it * @param _node A node to create the resource from * @param _replaceWithInstance if true (default), the node used as origin is replaced by a [[NodeResourceInstance]] of the [[NodeResource]] created */ static registerNodeAsResource(_node, _replaceWithInstance = true) { let serialization = _node.serialize(); let nodeResource = new FudgeCore.NodeResource("NodeResource"); nodeResource.deserialize(serialization); ResourceManager.register(nodeResource); if (_replaceWithInstance && _node.getParent()) { let instance = new FudgeCore.NodeResourceInstance(nodeResource); _node.getParent().replaceChild(_node, instance); } return nodeResource; } /** * Serialize all resources */ static serialize() { let serialization = {}; for (let idResource in ResourceManager.resources) { let resource = ResourceManager.resources[idResource]; if (idResource != resource.idResource) FudgeCore.Debug.error("Resource-id mismatch", resource); serialization[idResource] = FudgeCore.Serializer.serialize(resource); } return serialization; } /** * Create resources from a serialization, deleting all resources previously registered * @param _serialization */ static deserialize(_serialization) { ResourceManager.serialization = _serialization; ResourceManager.resources = {}; for (let idResource in _serialization) { let serialization = _serialization[idResource]; let resource = ResourceManager.deserializeResource(serialization); if (resource) ResourceManager.resources[idResource] = resource; } return ResourceManager.resources; } static deserializeResource(_serialization) { return FudgeCore.Serializer.deserialize(_serialization); } }
JavaScript
class EventTargetStatic extends EventTarget { constructor() { super(); } static addEventListener(_type, _handler) { EventTargetStatic.targetStatic.addEventListener(_type, _handler); } static removeEventListener(_type, _handler) { EventTargetStatic.targetStatic.removeEventListener(_type, _handler); } static dispatchEvent(_event) { EventTargetStatic.targetStatic.dispatchEvent(_event); return true; } }
JavaScript
class FramingFixed extends Framing { constructor() { super(...arguments); this.width = 300; this.height = 150; } setSize(_width, _height) { this.width = _width; this.height = _height; } getPoint(_pointInFrame, _rectFrame) { let result = new FudgeCore.Vector2(this.width * (_pointInFrame.x - _rectFrame.x) / _rectFrame.width, this.height * (_pointInFrame.y - _rectFrame.y) / _rectFrame.height); return result; } getPointInverse(_point, _rect) { let result = new FudgeCore.Vector2(_point.x * _rect.width / this.width + _rect.x, _point.y * _rect.height / this.height + _rect.y); return result; } getRect(_rectFrame) { return FudgeCore.Rectangle.GET(0, 0, this.width, this.height); } }
JavaScript
class FramingScaled extends Framing { constructor() { super(...arguments); this.normWidth = 1.0; this.normHeight = 1.0; } setScale(_normWidth, _normHeight) { this.normWidth = _normWidth; this.normHeight = _normHeight; } getPoint(_pointInFrame, _rectFrame) { let result = new FudgeCore.Vector2(this.normWidth * (_pointInFrame.x - _rectFrame.x), this.normHeight * (_pointInFrame.y - _rectFrame.y)); return result; } getPointInverse(_point, _rect) { let result = new FudgeCore.Vector2(_point.x / this.normWidth + _rect.x, _point.y / this.normHeight + _rect.y); return result; } getRect(_rectFrame) { return FudgeCore.Rectangle.GET(0, 0, this.normWidth * _rectFrame.width, this.normHeight * _rectFrame.height); } }
JavaScript
class FramingComplex extends Framing { constructor() { super(...arguments); this.margin = { left: 0, top: 0, right: 0, bottom: 0 }; this.padding = { left: 0, top: 0, right: 0, bottom: 0 }; } getPoint(_pointInFrame, _rectFrame) { let result = new FudgeCore.Vector2(_pointInFrame.x - this.padding.left - this.margin.left * _rectFrame.width, _pointInFrame.y - this.padding.top - this.margin.top * _rectFrame.height); return result; } getPointInverse(_point, _rect) { let result = new FudgeCore.Vector2(_point.x + this.padding.left + this.margin.left * _rect.width, _point.y + this.padding.top + this.margin.top * _rect.height); return result; } getRect(_rectFrame) { if (!_rectFrame) return null; let minX = _rectFrame.x + this.margin.left * _rectFrame.width + this.padding.left; let minY = _rectFrame.y + this.margin.top * _rectFrame.height + this.padding.top; let maxX = _rectFrame.x + (1 - this.margin.right) * _rectFrame.width - this.padding.right; let maxY = _rectFrame.y + (1 - this.margin.bottom) * _rectFrame.height - this.padding.bottom; return FudgeCore.Rectangle.GET(minX, minY, maxX - minX, maxY - minY); } getMutator() { return { margin: this.margin, padding: this.padding }; } }
JavaScript
class Rectangle extends FudgeCore.Mutable { constructor(_x = 0, _y = 0, _width = 1, _height = 1, _origin = ORIGIN2D.TOPLEFT) { super(); this.position = FudgeCore.Recycler.get(FudgeCore.Vector2); this.size = FudgeCore.Recycler.get(FudgeCore.Vector2); this.setPositionAndSize(_x, _y, _width, _height, _origin); } /** * Returns a new rectangle created with the given parameters */ static GET(_x = 0, _y = 0, _width = 1, _height = 1, _origin = ORIGIN2D.TOPLEFT) { let rect = FudgeCore.Recycler.get(Rectangle); rect.setPositionAndSize(_x, _y, _width, _height); return rect; } /** * Sets the position and size of the rectangle according to the given parameters */ setPositionAndSize(_x = 0, _y = 0, _width = 1, _height = 1, _origin = ORIGIN2D.TOPLEFT) { this.size.set(_width, _height); switch (_origin & 0x03) { case 0x00: this.position.x = _x; break; case 0x01: this.position.x = _x - _width / 2; break; case 0x02: this.position.x = _x - _width; break; } switch (_origin & 0x30) { case 0x00: this.position.y = _y; break; case 0x10: this.position.y = _y - _height / 2; break; case 0x20: this.position.y = _y - _height; break; } } get x() { return this.position.x; } get y() { return this.position.y; } get width() { return this.size.x; } get height() { return this.size.y; } get left() { return this.position.x; } get top() { return this.position.y; } get right() { return this.position.x + this.size.x; } get bottom() { return this.position.y + this.size.y; } set x(_x) { this.position.x = _x; } set y(_y) { this.position.y = _y; } set width(_width) { this.position.x = _width; } set height(_height) { this.position.y = _height; } set left(_value) { this.size.x = this.right - _value; this.position.x = _value; } set top(_value) { this.size.y = this.bottom - _value; this.position.y = _value; } set right(_value) { this.size.x = this.position.x + _value; } set bottom(_value) { this.size.y = this.position.y + _value; } /** * Returns true if the given point is inside of this rectangle or on the border * @param _point */ isInside(_point) { return (_point.x >= this.left && _point.x <= this.right && _point.y >= this.top && _point.y <= this.bottom); } reduceMutator(_mutator) { } }
JavaScript
class Mesh { constructor() { this.idResource = undefined; } static getBufferSpecification() { return { size: 3, dataType: WebGL2RenderingContext.FLOAT, normalize: false, stride: 0, offset: 0 }; } getVertexCount() { return this.vertices.length / Mesh.getBufferSpecification().size; } getIndexCount() { return this.indices.length; } // Serialize/Deserialize for all meshes that calculate without parameters serialize() { let serialization = { idResource: this.idResource }; // no data needed ... return serialization; } deserialize(_serialization) { this.create(); // TODO: must not be created, if an identical mesh already exists this.idResource = _serialization.idResource; return this; } }
JavaScript
class MeshPyramid extends FudgeCore.Mesh { constructor() { super(); this.create(); } create() { this.vertices = this.createVertices(); this.indices = this.createIndices(); this.textureUVs = this.createTextureUVs(); this.normalsFace = this.createFaceNormals(); } createVertices() { let vertices = new Float32Array([ // floor /*0*/ -1, 0, 1, /*1*/ 1, 0, 1, /*2*/ 1, 0, -1, /*3*/ -1, 0, -1, // tip /*4*/ 0, 2, 0, // floor again for texturing and normals /*5*/ -1, 0, 1, /*6*/ 1, 0, 1, /*7*/ 1, 0, -1, /*8*/ -1, 0, -1 ]); // scale down to a length of 1 for bottom edges and height vertices = vertices.map(_value => _value / 2); return vertices; } createIndices() { let indices = new Uint16Array([ // front 4, 0, 1, // right 4, 1, 2, // back 4, 2, 3, // left 4, 3, 0, // bottom 5 + 0, 5 + 2, 5 + 1, 5 + 0, 5 + 3, 5 + 2 ]); return indices; } createTextureUVs() { let textureUVs = new Float32Array([ // front /*0*/ 0, 1, /*1*/ 0.5, 1, /*2*/ 1, 1, /*3*/ 0.5, 1, // back /*4*/ 0.5, 0, /*5*/ 0, 0, /*6*/ 1, 0, /*7*/ 1, 1, /*8*/ 0, 1 ]); return textureUVs; } createFaceNormals() { let normals = []; let vertices = []; for (let v = 0; v < this.vertices.length; v += 3) vertices.push(new FudgeCore.Vector3(this.vertices[v], this.vertices[v + 1], this.vertices[v + 2])); for (let i = 0; i < this.indices.length; i += 3) { let vertex = [this.indices[i], this.indices[i + 1], this.indices[i + 2]]; let v0 = FudgeCore.Vector3.DIFFERENCE(vertices[vertex[0]], vertices[vertex[1]]); let v1 = FudgeCore.Vector3.DIFFERENCE(vertices[vertex[0]], vertices[vertex[2]]); let normal = FudgeCore.Vector3.NORMALIZATION(FudgeCore.Vector3.CROSS(v0, v1)); let index = vertex[2] * 3; normals[index] = normal.x; normals[index + 1] = normal.y; normals[index + 2] = normal.z; // normals.push(normal.x, normal.y, normal.z); } normals.push(0, 0, 0); return new Float32Array(normals); } }
JavaScript
class NodeResource extends FudgeCore.Node { constructor() { super(...arguments); this.idResource = undefined; } }
JavaScript
class NodeResourceInstance extends FudgeCore.Node { constructor(_nodeResource) { super("NodeResourceInstance"); /** id of the resource that instance was created from */ // TODO: examine, if this should be a direct reference to the NodeResource, instead of the id this.idSource = undefined; if (_nodeResource) this.set(_nodeResource); } /** * Recreate this node from the [[NodeResource]] referenced */ reset() { let resource = FudgeCore.ResourceManager.get(this.idSource); this.set(resource); } //TODO: optimize using the referenced NodeResource, serialize/deserialize only the differences serialize() { let serialization = super.serialize(); serialization.idSource = this.idSource; return serialization; } deserialize(_serialization) { super.deserialize(_serialization); this.idSource = _serialization.idSource; return this; } /** * Set this node to be a recreation of the [[NodeResource]] given * @param _nodeResource */ set(_nodeResource) { // TODO: examine, if the serialization should be stored in the NodeResource for optimization let serialization = FudgeCore.Serializer.serialize(_nodeResource); //Serializer.deserialize(serialization); for (let path in serialization) { this.deserialize(serialization[path]); break; } this.idSource = _nodeResource.idResource; this.dispatchEvent(new Event("nodeResourceInstantiated" /* NODERESOURCE_INSTANTIATED */)); } }
JavaScript
class Reference { constructor(_reference) { this.count = 0; this.reference = _reference; } getReference() { return this.reference; } increaseCounter() { this.count++; return this.count; } decreaseCounter() { if (this.count == 0) throw (new Error("Negative reference counter")); this.count--; return this.count; } }
JavaScript
class RenderManager extends FudgeCore.RenderOperator { // #region Adding /** * Register the node for rendering. Create a reference for it and increase the matching render-data references or create them first if necessary * @param _node */ static addNode(_node) { if (RenderManager.nodes.get(_node)) return; let cmpMaterial = _node.getComponent(FudgeCore.ComponentMaterial); if (!cmpMaterial) return; let shader = cmpMaterial.material.getShader(); RenderManager.createReference(RenderManager.renderShaders, shader, RenderManager.createProgram); let coat = cmpMaterial.material.getCoat(); RenderManager.createReference(RenderManager.renderCoats, coat, RenderManager.createParameter); let mesh = _node.getComponent(FudgeCore.ComponentMesh).mesh; RenderManager.createReference(RenderManager.renderBuffers, mesh, RenderManager.createBuffers); let nodeReferences = { shader: shader, coat: coat, mesh: mesh }; //, doneTransformToWorld: false }; RenderManager.nodes.set(_node, nodeReferences); } /** * Register the node and its valid successors in the branch for rendering using [[addNode]] * @param _node * @returns false, if the given node has a current timestamp thus having being processed during latest RenderManager.update and no addition is needed */ static addBranch(_node) { if (_node.isUpdated(RenderManager.timestampUpdate)) return false; for (let node of _node.branch) try { // may fail when some components are missing. TODO: cleanup RenderManager.addNode(node); } catch (_e) { FudgeCore.Debug.log(_e); } return true; } // #endregion // #region Removing /** * Unregister the node so that it won't be rendered any more. Decrease the render-data references and delete the node reference. * @param _node */ static removeNode(_node) { let nodeReferences = RenderManager.nodes.get(_node); if (!nodeReferences) return; RenderManager.removeReference(RenderManager.renderShaders, nodeReferences.shader, RenderManager.deleteProgram); RenderManager.removeReference(RenderManager.renderCoats, nodeReferences.coat, RenderManager.deleteParameter); RenderManager.removeReference(RenderManager.renderBuffers, nodeReferences.mesh, RenderManager.deleteBuffers); RenderManager.nodes.delete(_node); } /** * Unregister the node and its valid successors in the branch to free renderer resources. Uses [[removeNode]] * @param _node */ static removeBranch(_node) { for (let node of _node.branch) RenderManager.removeNode(node); } // #endregion // #region Updating /** * Reflect changes in the node concerning shader, coat and mesh, manage the render-data references accordingly and update the node references * @param _node */ static updateNode(_node) { let nodeReferences = RenderManager.nodes.get(_node); if (!nodeReferences) return; let cmpMaterial = _node.getComponent(FudgeCore.ComponentMaterial); let shader = cmpMaterial.material.getShader(); if (shader !== nodeReferences.shader) { RenderManager.removeReference(RenderManager.renderShaders, nodeReferences.shader, RenderManager.deleteProgram); RenderManager.createReference(RenderManager.renderShaders, shader, RenderManager.createProgram); nodeReferences.shader = shader; } let coat = cmpMaterial.material.getCoat(); if (coat !== nodeReferences.coat) { RenderManager.removeReference(RenderManager.renderCoats, nodeReferences.coat, RenderManager.deleteParameter); RenderManager.createReference(RenderManager.renderCoats, coat, RenderManager.createParameter); nodeReferences.coat = coat; } let mesh = (_node.getComponent(FudgeCore.ComponentMesh)).mesh; if (mesh !== nodeReferences.mesh) { RenderManager.removeReference(RenderManager.renderBuffers, nodeReferences.mesh, RenderManager.deleteBuffers); RenderManager.createReference(RenderManager.renderBuffers, mesh, RenderManager.createBuffers); nodeReferences.mesh = mesh; } } /** * Update the node and its valid successors in the branch using [[updateNode]] * @param _node */ static updateBranch(_node) { for (let node of _node.branch) RenderManager.updateNode(node); } // #endregion // #region Lights /** * Viewports collect the lights relevant to the branch to render and calls setLights to pass the collection. * RenderManager passes it on to all shaders used that can process light * @param _lights */ static setLights(_lights) { // let renderLights: RenderLights = RenderManager.createRenderLights(_lights); for (let entry of RenderManager.renderShaders) { let renderShader = entry[1].getReference(); RenderManager.setLightsInShader(renderShader, _lights); } // debugger; } // #endregion // #region Rendering /** * Update all render data. After RenderManager, multiple viewports can render their associated data without updating the same data multiple times */ static update() { RenderManager.timestampUpdate = performance.now(); RenderManager.recalculateAllNodeTransforms(); } /** * Clear the offscreen renderbuffer with the given [[Color]] * @param _color */ static clear(_color = null) { RenderManager.crc3.clearColor(_color.r, _color.g, _color.b, _color.a); RenderManager.crc3.clear(WebGL2RenderingContext.COLOR_BUFFER_BIT | WebGL2RenderingContext.DEPTH_BUFFER_BIT); } /** * Reset the offscreen framebuffer to the original RenderingContext */ static resetFrameBuffer(_color = null) { RenderManager.crc3.bindFramebuffer(WebGL2RenderingContext.FRAMEBUFFER, null); } /** * Draws the branch starting with the given [[Node]] using the camera given [[ComponentCamera]]. * @param _node * @param _cmpCamera */ static drawBranch(_node, _cmpCamera, _drawNode = RenderManager.drawNode) { if (_drawNode == RenderManager.drawNode) RenderManager.resetFrameBuffer(); let finalTransform; let cmpMesh = _node.getComponent(FudgeCore.ComponentMesh); if (cmpMesh) finalTransform = FudgeCore.Matrix4x4.MULTIPLICATION(_node.mtxWorld, cmpMesh.pivot); else finalTransform = _node.mtxWorld; // caution, RenderManager is a reference... // multiply camera matrix let projection = FudgeCore.Matrix4x4.MULTIPLICATION(_cmpCamera.ViewProjectionMatrix, finalTransform); _drawNode(_node, finalTransform, projection); for (let name in _node.getChildren()) { let childNode = _node.getChildren()[name]; RenderManager.drawBranch(childNode, _cmpCamera, _drawNode); //, world); } FudgeCore.Recycler.store(projection); if (finalTransform != _node.mtxWorld) FudgeCore.Recycler.store(finalTransform); } //#region RayCast & Picking /** * Draws the branch for RayCasting starting with the given [[Node]] using the camera given [[ComponentCamera]]. * @param _node * @param _cmpCamera */ static drawBranchForRayCast(_node, _cmpCamera) { RenderManager.pickBuffers = []; if (!RenderManager.renderShaders.get(FudgeCore.ShaderRayCast)) RenderManager.createReference(RenderManager.renderShaders, FudgeCore.ShaderRayCast, RenderManager.createProgram); RenderManager.drawBranch(_node, _cmpCamera, RenderManager.drawNodeForRayCast); RenderManager.resetFrameBuffer(); return RenderManager.pickBuffers; } static pickNodeAt(_pos, _pickBuffers, _rect) { let hits = []; for (let pickBuffer of _pickBuffers) { RenderManager.crc3.bindFramebuffer(WebGL2RenderingContext.FRAMEBUFFER, pickBuffer.frameBuffer); // TODO: instead of reading all data and afterwards pick the pixel, read only the pixel! let data = new Uint8Array(_rect.width * _rect.height * 4); RenderManager.crc3.readPixels(0, 0, _rect.width, _rect.height, WebGL2RenderingContext.RGBA, WebGL2RenderingContext.UNSIGNED_BYTE, data); let pixel = _pos.x + _rect.width * _pos.y; let zBuffer = data[4 * pixel + 2] + data[4 * pixel + 3] / 256; let hit = new FudgeCore.RayHit(pickBuffer.node, 0, zBuffer); hits.push(hit); } return hits; } static drawNode(_node, _finalTransform, _projection) { let references = RenderManager.nodes.get(_node); if (!references) return; // TODO: deal with partial references let bufferInfo = RenderManager.renderBuffers.get(references.mesh).getReference(); let coatInfo = RenderManager.renderCoats.get(references.coat).getReference(); let shaderInfo = RenderManager.renderShaders.get(references.shader).getReference(); RenderManager.draw(shaderInfo, bufferInfo, coatInfo, _finalTransform, _projection); } static drawNodeForRayCast(_node, _finalTransform, _projection) { // TODO: look into SSBOs! let target = RenderManager.getRayCastTexture(); const framebuffer = RenderManager.crc3.createFramebuffer(); // render to our targetTexture by binding the framebuffer RenderManager.crc3.bindFramebuffer(WebGL2RenderingContext.FRAMEBUFFER, framebuffer); // attach the texture as the first color attachment const attachmentPoint = WebGL2RenderingContext.COLOR_ATTACHMENT0; RenderManager.crc3.framebufferTexture2D(WebGL2RenderingContext.FRAMEBUFFER, attachmentPoint, WebGL2RenderingContext.TEXTURE_2D, target, 0); // set render target let references = RenderManager.nodes.get(_node); if (!references) return; // TODO: deal with partial references let pickBuffer = { node: _node, texture: target, frameBuffer: framebuffer }; RenderManager.pickBuffers.push(pickBuffer); let bufferInfo = RenderManager.renderBuffers.get(references.mesh).getReference(); RenderManager.drawForRayCast(RenderManager.pickBuffers.length, bufferInfo, _finalTransform, _projection); // make texture available to onscreen-display // IDEA: Iterate over textures, collect data if z indicates hit, sort by z } static getRayCastTexture() { // create to render to const targetTextureWidth = RenderManager.getViewportRectangle().width; const targetTextureHeight = RenderManager.getViewportRectangle().height; const targetTexture = RenderManager.crc3.createTexture(); RenderManager.crc3.bindTexture(WebGL2RenderingContext.TEXTURE_2D, targetTexture); { const internalFormat = WebGL2RenderingContext.RGBA8; const format = WebGL2RenderingContext.RGBA; const type = WebGL2RenderingContext.UNSIGNED_BYTE; RenderManager.crc3.texImage2D(WebGL2RenderingContext.TEXTURE_2D, 0, internalFormat, targetTextureWidth, targetTextureHeight, 0, format, type, null); // set the filtering so we don't need mips RenderManager.crc3.texParameteri(WebGL2RenderingContext.TEXTURE_2D, WebGL2RenderingContext.TEXTURE_MIN_FILTER, WebGL2RenderingContext.LINEAR); RenderManager.crc3.texParameteri(WebGL2RenderingContext.TEXTURE_2D, WebGL2RenderingContext.TEXTURE_WRAP_S, WebGL2RenderingContext.CLAMP_TO_EDGE); RenderManager.crc3.texParameteri(WebGL2RenderingContext.TEXTURE_2D, WebGL2RenderingContext.TEXTURE_WRAP_T, WebGL2RenderingContext.CLAMP_TO_EDGE); } return targetTexture; } //#endregion //#region Transformation of branch /** * Recalculate the world matrix of all registered nodes respecting their hierarchical relation. */ static recalculateAllNodeTransforms() { // inner function to be called in a for each node at the bottom of RenderManager function // function markNodeToBeTransformed(_nodeReferences: NodeReferences, _node: Node, _map: MapNodeToNodeReferences): void { // _nodeReferences.doneTransformToWorld = false; // } // inner function to be called in a for each node at the bottom of RenderManager function let recalculateBranchContainingNode = (_nodeReferences, _node, _map) => { // find uppermost ancestor not recalculated yet let ancestor = _node; let parent; while (true) { parent = ancestor.getParent(); if (!parent) break; if (_node.isUpdated(RenderManager.timestampUpdate)) break; ancestor = parent; } // TODO: check if nodes without meshes must be registered // use the ancestors parent world matrix to start with, or identity if no parent exists or it's missing a ComponenTransform let matrix = FudgeCore.Matrix4x4.IDENTITY; if (parent) matrix = parent.mtxWorld; // start recursive recalculation of the whole branch starting from the ancestor found RenderManager.recalculateTransformsOfNodeAndChildren(ancestor, matrix); }; // call the functions above for each registered node // RenderManager.nodes.forEach(markNodeToBeTransformed); RenderManager.nodes.forEach(recalculateBranchContainingNode); } /** * Recursive method receiving a childnode and its parents updated world transform. * If the childnode owns a ComponentTransform, its worldmatrix is recalculated and passed on to its children, otherwise its parents matrix * @param _node * @param _world */ static recalculateTransformsOfNodeAndChildren(_node, _world) { let world = _world; let cmpTransform = _node.cmpTransform; if (cmpTransform) world = FudgeCore.Matrix4x4.MULTIPLICATION(_world, cmpTransform.local); _node.mtxWorld = world; _node.timestampUpdate = RenderManager.timestampUpdate; for (let child of _node.getChildren()) { RenderManager.recalculateTransformsOfNodeAndChildren(child, world); } } // #endregion // #region Manage references to render data /** * Removes a reference to a program, parameter or buffer by decreasing its reference counter and deleting it, if the counter reaches 0 * @param _in * @param _key * @param _deletor */ static removeReference(_in, _key, _deletor) { let reference; reference = _in.get(_key); if (reference.decreaseCounter() == 0) { // The following deletions may be an optimization, not necessary to start with and maybe counterproductive. // If data should be used later again, it must then be reconstructed... _deletor(reference.getReference()); _in.delete(_key); } } /** * Increases the counter of the reference to a program, parameter or buffer. Creates the reference, if it's not existent. * @param _in * @param _key * @param _creator */ static createReference(_in, _key, _creator) { let reference; reference = _in.get(_key); if (reference) reference.increaseCounter(); else { let content = _creator(_key); reference = new Reference(content); reference.increaseCounter(); _in.set(_key, reference); } } }
JavaScript
class Shader { /** The type of coat that can be used with this shader to create a material */ static getCoat() { return null; } static getVertexShaderSource() { return null; } static getFragmentShaderSource() { return null; } }
JavaScript
class ShaderMatCap extends FudgeCore.Shader { static getCoat() { return FudgeCore.CoatMatCap; } static getVertexShaderSource() { return `#version 300 es in vec3 a_position; in vec3 a_normal; uniform mat4 u_projection; out vec2 tex_coords_smooth; flat out vec2 tex_coords_flat; void main() { mat4 normalMatrix = transpose(inverse(u_projection)); vec4 p = vec4(a_position, 1.0); vec4 normal4 = vec4(a_normal, 1.0); vec3 e = normalize( vec3( u_projection * p ) ); vec3 n = normalize( vec3(normalMatrix * normal4) ); vec3 r = reflect( e, n ); float m = 2. * sqrt( pow( r.x, 2. ) + pow( r.y, 2. ) + pow( r.z + 1., 2. ) ); tex_coords_smooth = r.xy / m + .5; tex_coords_flat = r.xy / m + .5; gl_Position = u_projection * vec4(a_position, 1.0); }`; } static getFragmentShaderSource() { return `#version 300 es precision mediump float; uniform vec4 u_tint_color; uniform float u_flatmix; uniform sampler2D u_texture; in vec2 tex_coords_smooth; flat in vec2 tex_coords_flat; out vec4 frag; void main() { vec2 tc = mix(tex_coords_smooth, tex_coords_flat, u_flatmix); frag = u_tint_color * texture(u_texture, tc) * 2.0; }`; } }
JavaScript
class ShaderRayCast extends FudgeCore.Shader { static getVertexShaderSource() { return `#version 300 es in vec3 a_position; uniform mat4 u_projection; void main() { gl_Position = u_projection * vec4(a_position, 1.0); }`; } static getFragmentShaderSource() { return `#version 300 es precision mediump float; precision highp int; uniform int u_id; out vec4 frag; void main() { float id = float(u_id)/ 256.0; float upperbyte = trunc(gl_FragCoord.z * 256.0) / 256.0; float lowerbyte = fract(gl_FragCoord.z * 256.0); frag = vec4(id, id, upperbyte , lowerbyte); }`; } }
JavaScript
class TextureImage extends Texture { constructor() { super(...arguments); this.image = null; } }
JavaScript
class Time extends EventTarget { constructor() { super(); this.timers = {}; this.idTimerNext = 0; this.start = performance.now(); this.scale = 1.0; this.offset = 0.0; this.lastCallToElapsed = 0.0; } /** * Returns the game-time-object which starts automatically and serves as base for various internal operations. */ static get game() { return Time.gameTime; } /** * Retrieves the current scaled timestamp of this instance in milliseconds */ get() { return this.offset + this.scale * (performance.now() - this.start); } /** * (Re-) Sets the timestamp of this instance * @param _time The timestamp to represent the current time (default 0.0) */ set(_time = 0) { this.offset = _time; this.start = performance.now(); this.getElapsedSincePreviousCall(); } /** * Sets the scaling of this time, allowing for slowmotion (<1) or fastforward (>1) * @param _scale The desired scaling (default 1.0) */ setScale(_scale = 1.0) { this.set(this.get()); this.scale = _scale; //TODO: catch scale=0 this.rescaleAllTimers(); this.getElapsedSincePreviousCall(); this.dispatchEvent(new Event("timeScaled" /* TIME_SCALED */)); } /** * Retrieves the current scaling of this time */ getScale() { return this.scale; } /** * Retrieves the offset of this time */ getOffset() { return this.offset; } /** * Retrieves the scaled time in milliseconds passed since the last call to this method * Automatically reset at every call to set(...) and setScale(...) */ getElapsedSincePreviousCall() { let current = this.get(); let elapsed = current - this.lastCallToElapsed; this.lastCallToElapsed = current; return elapsed; } //#region Timers // TODO: examine if web-workers would enhance performance here! /** * See Javascript documentation. Creates an internal [[Timer]] object * @param _callback * @param _timeout * @param _arguments */ setTimeout(_callback, _timeout, ..._arguments) { return this.setTimer(TIMER_TYPE.TIMEOUT, _callback, _timeout, _arguments); } /** * See Javascript documentation. Creates an internal [[Timer]] object * @param _callback * @param _timeout * @param _arguments */ setInterval(_callback, _timeout, ..._arguments) { return this.setTimer(TIMER_TYPE.INTERVAL, _callback, _timeout, _arguments); } /** * See Javascript documentation * @param _id */ clearTimeout(_id) { this.deleteTimer(_id); } /** * See Javascript documentation * @param _id */ clearInterval(_id) { this.deleteTimer(_id); } /** * Stops and deletes all [[Timer]]s attached. Should be called before this Time-object leaves scope */ clearAllTimers() { for (let id in this.timers) { this.deleteTimer(Number(id)); } } /** * Recreates [[Timer]]s when scaling changes */ rescaleAllTimers() { for (let id in this.timers) { let timer = this.timers[id]; timer.clear(); if (!this.scale) // Time has stopped, no need to replace cleared timers continue; let timeout = timer.timeout; // if (timer.type == TIMER_TYPE.TIMEOUT && timer.active) // // for an active timeout-timer, calculate the remaining time to timeout // timeout = (performance.now() - timer.startTimeReal) / timer.timeoutReal; let replace = new Timer(this, timer.type, timer.callback, timeout, timer.arguments); this.timers[id] = replace; } } /** * Deletes [[Timer]] found using the id of the connected interval/timeout-object * @param _id */ deleteTimerByInternalId(_id) { for (let id in this.timers) { let timer = this.timers[id]; if (timer.id == _id) { timer.clear(); delete this.timers[id]; } } } setTimer(_type, _callback, _timeout, _arguments) { let timer = new Timer(this, _type, _callback, _timeout, _arguments); this.timers[++this.idTimerNext] = timer; return this.idTimerNext; } deleteTimer(_id) { this.timers[_id].clear(); delete this.timers[_id]; } }
JavaScript
class Loop extends FudgeCore.EventTargetStatic { /** * Starts the loop with the given mode and fps * @param _mode * @param _fps Is only applicable in TIME-modes * @param _syncWithAnimationFrame Experimental and only applicable in TIME-modes. Should defer the loop-cycle until the next possible animation frame. */ static start(_mode = LOOP_MODE.FRAME_REQUEST, _fps = 60, _syncWithAnimationFrame = false) { Loop.stop(); Loop.timeStartGame = FudgeCore.Time.game.get(); Loop.timeStartReal = performance.now(); Loop.timeLastFrameGame = Loop.timeStartGame; Loop.timeLastFrameReal = Loop.timeStartReal; Loop.fpsDesired = (_mode == LOOP_MODE.FRAME_REQUEST) ? 60 : _fps; Loop.framesToAverage = Loop.fpsDesired; Loop.timeLastFrameGameAvg = Loop.timeLastFrameRealAvg = 1000 / Loop.fpsDesired; Loop.mode = _mode; Loop.syncWithAnimationFrame = _syncWithAnimationFrame; let log = `Loop starting in mode ${Loop.mode}`; if (Loop.mode != LOOP_MODE.FRAME_REQUEST) log += ` with attempted ${_fps} fps`; FudgeCore.Debug.log(log); switch (_mode) { case LOOP_MODE.FRAME_REQUEST: Loop.loopFrame(); break; case LOOP_MODE.TIME_REAL: Loop.idIntervall = window.setInterval(Loop.loopTime, 1000 / Loop.fpsDesired); Loop.loopTime(); break; case LOOP_MODE.TIME_GAME: Loop.idIntervall = FudgeCore.Time.game.setInterval(Loop.loopTime, 1000 / Loop.fpsDesired); Loop.loopTime(); break; default: break; } Loop.running = true; } /** * Stops the loop */ static stop() { if (!Loop.running) return; switch (Loop.mode) { case LOOP_MODE.FRAME_REQUEST: window.cancelAnimationFrame(Loop.idRequest); break; case LOOP_MODE.TIME_REAL: window.clearInterval(Loop.idIntervall); window.cancelAnimationFrame(Loop.idRequest); break; case LOOP_MODE.TIME_GAME: // TODO: DANGER! id changes internally in game when time is scaled! FudgeCore.Time.game.clearInterval(Loop.idIntervall); window.cancelAnimationFrame(Loop.idRequest); break; default: break; } FudgeCore.Debug.log("Loop stopped!"); } static getFpsGameAverage() { return 1000 / Loop.timeLastFrameGameAvg; } static getFpsRealAverage() { return 1000 / Loop.timeLastFrameRealAvg; } static loop() { let time; time = performance.now(); Loop.timeFrameReal = time - Loop.timeLastFrameReal; Loop.timeLastFrameReal = time; time = FudgeCore.Time.game.get(); Loop.timeFrameGame = time - Loop.timeLastFrameGame; Loop.timeLastFrameGame = time; Loop.timeLastFrameGameAvg = ((Loop.framesToAverage - 1) * Loop.timeLastFrameGameAvg + Loop.timeFrameGame) / Loop.framesToAverage; Loop.timeLastFrameRealAvg = ((Loop.framesToAverage - 1) * Loop.timeLastFrameRealAvg + Loop.timeFrameReal) / Loop.framesToAverage; let event = new Event("loopFrame" /* LOOP_FRAME */); Loop.targetStatic.dispatchEvent(event); } static loopFrame() { Loop.loop(); Loop.idRequest = window.requestAnimationFrame(Loop.loopFrame); } static loopTime() { if (Loop.syncWithAnimationFrame) Loop.idRequest = window.requestAnimationFrame(Loop.loop); else Loop.loop(); } }
JavaScript
class FileIoBrowserLocal extends FudgeCore.EventTargetStatic { // TODO: refactor to async function to be handled using promise, instead of using event target static load() { FileIoBrowserLocal.selector = document.createElement("input"); FileIoBrowserLocal.selector.type = "file"; FileIoBrowserLocal.selector.multiple = true; FileIoBrowserLocal.selector.hidden = true; FileIoBrowserLocal.selector.addEventListener("change", FileIoBrowserLocal.handleFileSelect); document.body.appendChild(FileIoBrowserLocal.selector); FileIoBrowserLocal.selector.click(); } // TODO: refactor to async function to be handled using promise, instead of using event target static save(_toSave) { for (let filename in _toSave) { let content = _toSave[filename]; let blob = new Blob([content], { type: "text/plain" }); let url = window.URL.createObjectURL(blob); //*/ using anchor element for download let downloader; downloader = document.createElement("a"); downloader.setAttribute("href", url); downloader.setAttribute("download", filename); document.body.appendChild(downloader); downloader.click(); document.body.removeChild(downloader); window.URL.revokeObjectURL(url); } let event = new CustomEvent("fileSaved" /* FILE_SAVED */, { detail: { mapFilenameToContent: _toSave } }); FileIoBrowserLocal.targetStatic.dispatchEvent(event); } static async handleFileSelect(_event) { console.log("-------------------------------- handleFileSelect"); document.body.removeChild(FileIoBrowserLocal.selector); let fileList = _event.target.files; console.log(fileList, fileList.length); if (fileList.length == 0) return; let loaded = {}; await FileIoBrowserLocal.loadFiles(fileList, loaded); let event = new CustomEvent("fileLoaded" /* FILE_LOADED */, { detail: { mapFilenameToContent: loaded } }); FileIoBrowserLocal.targetStatic.dispatchEvent(event); } static async loadFiles(_fileList, _loaded) { for (let file of _fileList) { const content = await new Response(file).text(); _loaded[file.name] = content; } } }
JavaScript
class Logger { /** * Upon instantiation configure the logging levels and transports * * @param {array} transports The transport layers to use */ constructor(transports) { this.transports = { [LoggingLevels.levels.info]: [], [LoggingLevels.levels.debug]: [], [LoggingLevels.levels.notice]: [], [LoggingLevels.levels.warning]: [], [LoggingLevels.levels.error]: [], }; transports.forEach((transport) => transport.levels.forEach( (level) => this.transports[level] && this.transports[level].push(transport), ) ); } /** * Call the log method on the given transports with the given args * * @param {string} level LoggingLevels level that we are logging at * @param {array} args The args that we are logging, usually strings */ log(level, args) { const date = this.getDate(new Date()); this.transports[level].forEach( (transport) => transport.log(date, level, args), ); } /** * Info logging method * * @param {array} args The args to log */ info(...args) { this.log( LoggingLevels.levels.info, args, ); } /** * Debug logging method * * @param {array} args The args to log */ debug(...args) { this.log( LoggingLevels.levels.debug, args, ); } /** * Notice logging method * * @param {array} args The args to log */ notice(...args) { this.log( LoggingLevels.levels.notice, args, ); } /** * Warning logging method * * @param {array} args The args to log */ warning(...args) { this.log( LoggingLevels.levels.warning, args, ); } /** * Error logging method * * @param {array} args The args to log */ error(...args) { this.log( LoggingLevels.levels.error, args, ); } /** * Get the date in a yyyy-mm-dd format * * @param {date} date A date object * * @return {string} */ getDate(date) { return [ date.getFullYear(), this.padNumberStringLessThanTen(date.getMonth()+1), this.padNumberStringLessThanTen(date.getDate()), ].join('-') + ' ' + [ this.padNumberStringLessThanTen(date.getHours()), this.padNumberStringLessThanTen(date.getMinutes()), this.padNumberStringLessThanTen(date.getSeconds()), ].join(':'); } /** * Pad values lower than 10 with a 0 for printing * * @param {number} val A number to pad * * @return {string} */ padNumberStringLessThanTen(val) { return val < 10 ? '0' + val : val; } }
JavaScript
class TuberculosisDataset { constructor() { this.trainData = []; this.testData = []; } /** Loads training and test data. */ loadData() { console.log('Loading images...'); this.trainData = loadImages(TRAIN_IMAGES_DIR); this.testData = loadImages(TEST_IMAGES_DIR); console.log('Images loaded successfully.') } getTrainData() { return { images: tf.concat(this.trainData[0]), labels: tf.oneHot(tf.tensor1d(this.trainData[1], 'int32'), 2).toFloat() } } getTestData() { return { images: tf.concat(this.testData[0]), labels: tf.oneHot(tf.tensor1d(this.testData[1], 'int32'), 2).toFloat() } } }
JavaScript
class PiechartController { constructor($state) { "ngInject"; this.$state = $state; this.initPieChart(); } initPieChart() { let self = this; self.pieConfig = { theme: 'default', dataLoaded: true }; self.pieOption = { tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { orient: 'vertical', x: '65%', top: '25%', data: ['正常', '断开', '等待'], formatter: function (name) { var oa = self.pieOption.series[0].data; for (var i = 0; i < self.pieOption.series[0].data.length; i++) { if (name == oa[i].name) { return name + ':' + oa[i].value + '个'; } } } }, color: ['#bdea75', '#fe5454', '#faba3c'], series: [{ name: '比例分析', type: 'pie', radius: '55%', center: ['35%', '50%'], data: [{ value: '2', name: '正常' }, { value: '2', name: '断开' }, { value: '2', name: '等待' }], itemStyle: { normal: { label: { show: false, formatter: '{b} : {c} ({d}%)' } }, labelLine: { show: true } } }] }; } }
JavaScript
class TimersScalePlugin extends SliderPlugin { /** * Creates an instance of TimersScalePlugin. * @param {string | HTMLElement} timersScaleSliders selector string or HTML Element for the input(s) * @param {number} [defaultTimersScale=0.5] Default Value for the timer scale slider * @memberof TimersScalePlugin */ constructor(timersScaleSliders, { defaultTimersScale = 0.5 } = {}) { super(timersScaleSliders, 'Timers-Scale-Plugin', { defaultValue: defaultTimersScale, featureName: TimersScalePlugin.timersScaleKey }); for (let i = 0; i < this.slidersLength; i++) { this.sliders[i].enableSliderEvents(this.onTimersScaleChange.bind(this)); } } /** * @memberof TimersScalePlugin * @param {Event} e */ onTimersScaleChange(e) { this.currentValue = e.target.value; this.sendProperty(TimersScalePlugin.timersScaleKey, this.currentValue); } /** * @readonly * @static * @memberof TimersScalePlugin * @return {string} */ static get timersScaleKey() { return 'timersScale'; } }
JavaScript
class DateType extends avro.types.LogicalType { _fromValue(val) { return new Date(val); } _toValue(any) { if (any !== null && (any instanceof Date || !isNaN(any))) { return +any; } } _resolve(type) { if (avro.Type.isType(type, 'long', 'string')) { return this._fromValue; } } }
JavaScript
class Finder extends Component { constructor(props){ super(props); this.state = { theme: props.theme, finderMenu: props.finderMenu, osMenu: props.osMenu, currentPID: 0, currentWindow: undefined, openWindows: [], } } render(){ const { theme, finderMenu, osMenu, } = this.state; return( <ThemeProvider theme={theme}> <WindowProvider> <ApplicationProvider> <AppAPI> { appAPI => ( <main> <Desktop> <Icon src="../data/img/se.svg" label="MelloOS" actionHandler={ (e) => appAPI.openApp(e, "../data/img/se.svg")} /> <Icon src="../data/img/trash.svg" label="Trash" top={window.innerHeight - 100} actionHandler={ () => appAPI.openApp("clock", "../data/img/se.svg")} /> </Desktop> <MenuBar appMenu={finderMenu} osMenu={osMenu} statusMenu={[<Clock />]} actionHandler={appAPI.openApp} /> <WindowManager /> </main> )} </AppAPI> </ApplicationProvider> </WindowProvider> </ThemeProvider> ) } }
JavaScript
class RTreePyramid { /** * Instantiates a new RTreePyramid object. * * @param {object} options - The options object. * @param {boolean} options.nodeCapacity - The node capacity of the r-tree. */ constructor(options) { this.trees = new Map(); this.collidables = new Map(); this.nodeCapacity = defaultTo(options.nodeCapacity, 32); } /** * Inserts an array of collidables into the r-tree for the provided coord. * * @param {TileCoord} coord - The coord of the tile. * @param {Array} collidables - The array of collidables to insert. * * @returns {RTreePyramid} The RTreePyramid object, for chaining. */ insert(coord, collidables) { if (!this.trees.has(coord.z)) { this.trees.set(coord.z, new RTree({ nodeCapacity: this.nodeCapacity })); } this.trees.get(coord.z).insert(collidables); this.collidables.set(coord.hash, collidables); return this; } /** * Removes an array of collidables from the r-tree for the provided coord. * * @param {TileCoord} coord - The coord of the tile. * * @returns {RTreePyramid} The RTreePyramid object, for chaining. */ remove(coord) { const collidables = this.collidables.get(coord.hash); this.trees.get(coord.z).remove(collidables); this.collidables.delete(coord.hash); return this; } /** * Searchs the r-tree using a point. * * @param {number} x - The x component. * @param {number} y - The y component. * @param {number} zoom - The zoom level of the plot. * @param {number} extent - The pixel extent of the plot zoom. * * @returns {object} The collision object. */ searchPoint(x, y, zoom, extent) { // points are stored in un-scaled coordinates, unscale the point const tileZoom = Math.round(zoom); // get the tree for the zoom const tree = this.trees.get(tileZoom); if (!tree) { // no data for tile return null; } const scale = Math.pow(2, tileZoom - zoom); // unscaled points const sx = x * extent * scale; const sy = y * extent * scale; // get collision return tree.searchPoint(sx, sy); } /** * Searchs the r-tree using a rectangle. * * @param {number} minX - The minimum x component. * @param {number} maxX - The maximum x component. * @param {number} minY - The minimum y component. * @param {number} maxY - The maximum y component. * @param {number} zoom - The zoom level of the plot. * @param {number} extent - The pixel extent of the plot zoom. * * @returns {object} The collision object. */ searchRectangle(minX, maxX, minY, maxY, zoom, extent) { // points are stored in un-scaled coordinates, unscale the point const tileZoom = Math.round(zoom); // get the tree for the zoom const tree = this.trees.get(tileZoom); if (!tree) { // no data for tile return null; } const scale = Math.pow(2, tileZoom - zoom); // unscaled points const sminX = minX * extent * scale; const smaxX = maxX * extent * scale; const sminY = minY * extent * scale; const smaxY = maxY * extent * scale; // get collision return tree.searchRectangle(sminX, smaxX, sminY, smaxY); } }
JavaScript
class IssueChangeChanges { /** * Constructs a new <code>IssueChangeChanges</code>. * @alias module:model/IssueChangeChanges */ constructor() { IssueChangeChanges.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>IssueChangeChanges</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/IssueChangeChanges} obj Optional instance to populate. * @return {module:model/IssueChangeChanges} The populated <code>IssueChangeChanges</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new IssueChangeChanges(); if (data.hasOwnProperty('assignee')) { obj['assignee'] = IssueChangeChangesAssignee.constructFromObject(data['assignee']); } if (data.hasOwnProperty('state')) { obj['state'] = IssueChangeChangesAssignee.constructFromObject(data['state']); } if (data.hasOwnProperty('title')) { obj['title'] = IssueChangeChangesAssignee.constructFromObject(data['title']); } if (data.hasOwnProperty('kind')) { obj['kind'] = IssueChangeChangesAssignee.constructFromObject(data['kind']); } if (data.hasOwnProperty('milestone')) { obj['milestone'] = IssueChangeChangesAssignee.constructFromObject(data['milestone']); } if (data.hasOwnProperty('component')) { obj['component'] = IssueChangeChangesAssignee.constructFromObject(data['component']); } if (data.hasOwnProperty('priority')) { obj['priority'] = IssueChangeChangesAssignee.constructFromObject(data['priority']); } if (data.hasOwnProperty('version')) { obj['version'] = IssueChangeChangesAssignee.constructFromObject(data['version']); } if (data.hasOwnProperty('content')) { obj['content'] = IssueChangeChangesAssignee.constructFromObject(data['content']); } } return obj; } }
JavaScript
class Navbar extends HTMLElement { constructor() { super(); // Create a shadow root const shadow = this.attachShadow({ mode: "open" }); // Create elements const linkElem = document.createElement("link"); const navBar = document.createElement("navbar"); // Apply external styles to the shadow dom linkElem.setAttribute("rel", "stylesheet"); linkElem.setAttribute("href", "../../static/css/bootstrap.min.css"); // Inject html code for navigation bar navBar.innerHTML = ` <nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="/" data-link>Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class=" nav-item"> <a class="nav__link nav-link" href="/news" data-link>News</a> </li> <li class="nav-item"> <a class="nav__link nav-link" href="/contact" data-link>Careers</a> </li> </ul> </div> </div> </nav> `; // Attach the created elements to the shadow dom shadow.appendChild(linkElem); shadow.appendChild(navBar); } }
JavaScript
class LineGeometry { constructor() { this.vertices = []; this.vertexColors = []; this.indices = []; } }
JavaScript
class LineGroup { constructor(hasNormalsAndUvs = false, highPrecision = false, isSimple = false) { this.hasNormalsAndUvs = hasNormalsAndUvs; this.highPrecision = highPrecision; this.isSimple = isSimple; this.m_geometry = new LineGeometry(); } /** * Adds all the attribute data needed to a [[BufferGeometry]] object for rendering `Lines`. * * @param vertices - Array of vertex attributes. * @param colors - Array of vertex colors. * @param indices - Array of vertex indices. * @param geometry - [[BufferGeometry]] object which will store all the `Lines` attribute data. * @param hasNormalsAnUvs - Whether vertices have normal and uv coordinates as attributes. * @param highPrecision - If `true` will create high-precision vertex information. * @param isSimple - `true` to create simple (nonsolid, nonextruded) lines. Defaults to `false`. */ static createGeometry(vertices, colors, indices, geometry, hasNormalsAndUvs = false, highPrecision = false, isSimple = false) { if (isSimple) { geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(vertices), 3)); if (colors.length === vertices.length) { geometry.setAttribute("color", new THREE.BufferAttribute(new Float32Array(colors), 3)); } geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1)); return geometry; } else { const vertexDescriptor = getVertexDescriptor(hasNormalsAndUvs, highPrecision); const buffer = new THREE.InterleavedBuffer(new Float32Array(vertices), vertexDescriptor.stride); vertexDescriptor.attributes.forEach(descr => { const attribute = new THREE.InterleavedBufferAttribute(buffer, descr.itemSize, descr.offset, false); geometry.setAttribute(descr.name, attribute); }); if (colors.length === vertices.length) { geometry.setAttribute("color", new THREE.BufferAttribute(new Float32Array(colors), 3)); } geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1)); return geometry; } } /** * Clears the list of line strips. */ clear() { this.m_geometry.vertices = []; this.m_geometry.vertexColors = []; this.m_geometry.indices = []; } /** * Add the given points to this line group. * * @param center - World center of the provided points. * @param points - Sequence of (x,y,z) coordinates. * @param offsets - Sequence of line segment offsets. * @param uvs - Sequence of (u,v) texture coordinates. * @param colors - Sequence of (r,g,b) color components. */ add(center, points, projection, offsets, uvs, colors) { if (!this.isSimple) { harp_utils_1.assert(!this.hasNormalsAndUvs || uvs !== undefined); createLineGeometry(center, points, projection, offsets, uvs, colors, this.m_geometry, this.highPrecision); } else { createSimpleLineGeometry(points, colors, this.m_geometry); } return this; } /** * Returns the list of vertices. */ get vertices() { return this.m_geometry.vertices; } /** * Returns the list of vertex colors. */ get vertexColors() { return this.m_geometry.vertexColors; } /** * Returns the list of indices. */ get indices() { return this.m_geometry.indices; } /** * Returns the list of [[VertexAttributeDescriptor]]s. */ get vertexAttributes() { return getVertexDescriptor(this.hasNormalsAndUvs, this.highPrecision).attributes; } /** * Returns the vertex attribute stride. */ get stride() { return getVertexDescriptor(this.hasNormalsAndUvs, this.highPrecision).stride; } /** * Creates a three.js geometry. */ createGeometry(geometry) { if (geometry === undefined) { geometry = new THREE.BufferGeometry(); } return LineGroup.createGeometry(this.m_geometry.vertices, this.m_geometry.vertexColors, this.m_geometry.indices, geometry, this.hasNormalsAndUvs, this.highPrecision); } }
JavaScript
class ImageHelper { /** * Convert the data to an image source. * @param mimeType The mime type of the data. * @param data The source data. * @returns The image source. */ static dataToImageSource(mimeType, data) { if (stringHelper_1.StringHelper.isEmpty(mimeType)) { throw new Error("You must provider a mimeType"); } let imageSource; if (objectHelper_1.ObjectHelper.isType(data, Uint8Array)) { let binary = ""; const len = data.length; for (let i = 0; i < len; i++) { binary += String.fromCharCode(data[i]); } const base64Data = btoa(binary); imageSource = `data:${mimeType};base64,${base64Data}`; } else if (stringHelper_1.StringHelper.isString(data)) { const base64Data = btoa(data); imageSource = `data:${mimeType};base64,${base64Data}`; } else { throw new Error("The data must be a Uint8Array or string"); } return imageSource; } }
JavaScript
class Node { constructor(valor, izq = null, der = null) { this.valor = valor; this.izq = izq; this.der = der; } }
JavaScript
class JacobianPoint { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } static fromAffine(p) { if (!(p instanceof Point)) { throw new TypeError('JacobianPoint#fromAffine: expected Point'); } return new JacobianPoint(p.x, p.y, _1n$1); } // Takes a bunch of Jacobian Points but executes only one // invert on all of them. invert is very slow operation, // so this improves performance massively. static toAffineBatch(points) { const toInv = invertBatch(points.map(p => p.z)); return points.map((p, i) => p.toAffine(toInv[i])); } static normalizeZ(points) { return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine); } // Compare one point to another. equals(other) { const a = this; const b = other; const az2 = mod(a.z * a.z); const az3 = mod(a.z * az2); const bz2 = mod(b.z * b.z); const bz3 = mod(b.z * bz2); return mod(a.x * bz2) === mod(az2 * b.x) && mod(a.y * bz3) === mod(az3 * b.y); } // Flips point to one corresponding to (x, -y) in Affine coordinates. negate() { return new JacobianPoint(this.x, mod(-this.y), this.z); } // Fast algo for doubling 2 Jacobian Points when curve's a=0. // Note: cannot be reused for other curves when a != 0. // From: http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l // Cost: 2M + 5S + 6add + 3*2 + 1*3 + 1*8. double() { const X1 = this.x; const Y1 = this.y; const Z1 = this.z; const A = mod(X1 ** _2n$1); const B = mod(Y1 ** _2n$1); const C = mod(B ** _2n$1); const D = mod(_2n$1 * (mod(mod((X1 + B) ** _2n$1)) - A - C)); const E = mod(_3n * A); const F = mod(E ** _2n$1); const X3 = mod(F - _2n$1 * D); const Y3 = mod(E * (D - X3) - _8n * C); const Z3 = mod(_2n$1 * Y1 * Z1); return new JacobianPoint(X3, Y3, Z3); } // Fast algo for adding 2 Jacobian Points when curve's a=0. // Note: cannot be reused for other curves when a != 0. // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-1998-cmo-2 // Cost: 12M + 4S + 6add + 1*2. // Note: 2007 Bernstein-Lange (11M + 5S + 9add + 4*2) is actually *slower*. No idea why. add(other) { if (!(other instanceof JacobianPoint)) { throw new TypeError('JacobianPoint#add: expected JacobianPoint'); } const X1 = this.x; const Y1 = this.y; const Z1 = this.z; const X2 = other.x; const Y2 = other.y; const Z2 = other.z; if (X2 === _0n$1 || Y2 === _0n$1) return this; if (X1 === _0n$1 || Y1 === _0n$1) return other; const Z1Z1 = mod(Z1 ** _2n$1); const Z2Z2 = mod(Z2 ** _2n$1); const U1 = mod(X1 * Z2Z2); const U2 = mod(X2 * Z1Z1); const S1 = mod(Y1 * Z2 * Z2Z2); const S2 = mod(mod(Y2 * Z1) * Z1Z1); const H = mod(U2 - U1); const r = mod(S2 - S1); // H = 0 meaning it's the same point. if (H === _0n$1) { if (r === _0n$1) { return this.double(); } else { return JacobianPoint.ZERO; } } const HH = mod(H ** _2n$1); const HHH = mod(H * HH); const V = mod(U1 * HH); const X3 = mod(r ** _2n$1 - HHH - _2n$1 * V); const Y3 = mod(r * (V - X3) - S1 * HHH); const Z3 = mod(Z1 * Z2 * H); return new JacobianPoint(X3, Y3, Z3); } subtract(other) { return this.add(other.negate()); } // Non-constant-time multiplication. Uses double-and-add algorithm. // It's faster, but should only be used when you don't care about // an exposed private key e.g. sig verification, which works over *public* keys. multiplyUnsafe(scalar) { let n = normalizeScalar(scalar); // The condition is not executed unless you change global var if (!USE_ENDOMORPHISM) { let p = JacobianPoint.ZERO; let d = this; while (n > _0n$1) { if (n & _1n$1) p = p.add(d); d = d.double(); n >>= _1n$1; } return p; } let { k1neg, k1, k2neg, k2 } = splitScalarEndo(n); let k1p = JacobianPoint.ZERO; let k2p = JacobianPoint.ZERO; let d = this; while (k1 > _0n$1 || k2 > _0n$1) { if (k1 & _1n$1) k1p = k1p.add(d); if (k2 & _1n$1) k2p = k2p.add(d); d = d.double(); k1 >>= _1n$1; k2 >>= _1n$1; } if (k1neg) k1p = k1p.negate(); if (k2neg) k2p = k2p.negate(); k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z); return k1p.add(k2p); } // Creates a wNAF precomputation window. // Used for caching. // Default window size is set by `utils.precompute()` and is equal to 8. // Which means we are caching 65536 points: 256 points for every bit from 0 to 256. precomputeWindow(W) { // splitScalarEndo could return 129-bit numbers, so we need at least 128 / W + 1 const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; let points = []; let p = this; let base = p; for (let window = 0; window < windows; window++) { base = p; points.push(base); for (let i = 1; i < 2 ** (W - 1); i++) { base = base.add(p); points.push(base); } p = base.double(); } return points; } // Implements w-ary non-adjacent form for calculating ec multiplication // Optional `affinePoint` argument is used to save cached precompute windows on it. wNAF(n, affinePoint) { if (!affinePoint && this.equals(JacobianPoint.BASE)) affinePoint = Point.BASE; const W = affinePoint && affinePoint._WINDOW_SIZE || 1; if (256 % W) { throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2'); } // Calculate precomputes on a first run, reuse them after let precomputes = affinePoint && pointPrecomputes.get(affinePoint); if (!precomputes) { precomputes = this.precomputeWindow(W); if (affinePoint && W !== 1) { precomputes = JacobianPoint.normalizeZ(precomputes); pointPrecomputes.set(affinePoint, precomputes); } } // Initialize real and fake points for const-time let p = JacobianPoint.ZERO; let f = JacobianPoint.ZERO; const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1; const windowSize = 2 ** (W - 1); // W=8 128 const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b11111111 for W=8 const maxNumber = 2 ** W; // W=8 256 const shiftBy = BigInt(W); // W=8 8 // TODO: review this more carefully for (let window = 0; window < windows; window++) { const offset = window * windowSize; // Extract W bits. let wbits = Number(n & mask); // Shift number by W bits. n >>= shiftBy; // If the bits are bigger than max size, we'll split those. // +224 => 256 - 32 if (wbits > windowSize) { wbits -= maxNumber; n += _1n$1; } // Check if we're onto Zero point. // Add random point inside current window to f. if (wbits === 0) { // The most important part for const-time getPublicKey let pr = precomputes[offset]; if (window % 2) pr = pr.negate(); f = f.add(pr); } else { let cached = precomputes[offset + Math.abs(wbits) - 1]; if (wbits < 0) cached = cached.negate(); p = p.add(cached); } } return { p, f }; } // Constant time multiplication. // Uses wNAF method. Windowed method may be 10% faster, // but takes 2x longer to generate and consumes 2x memory. multiply(scalar, affinePoint) { let n = normalizeScalar(scalar); // Real point. let point; // Fake point, we use it to achieve constant-time multiplication. let fake; if (USE_ENDOMORPHISM) { let { k1neg, k1, k2neg, k2 } = splitScalarEndo(n); let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint); let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint); if (k1neg) k1p = k1p.negate(); if (k2neg) k2p = k2p.negate(); k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z); point = k1p.add(k2p); fake = f1p.add(f2p); } else { let { p, f } = this.wNAF(n, affinePoint); point = p; fake = f; } // Normalize `z` for both points, but return only real one return JacobianPoint.normalizeZ([point, fake])[0]; } // Converts Jacobian point to affine (x, y) coordinates. // Can accept precomputed Z^-1 - for example, from invertBatch. // (x, y, z) ∋ (x=x/z², y=y/z³) toAffine(invZ = invert(this.z)) { const invZ2 = invZ ** _2n$1; const x = mod(this.x * invZ2); const y = mod(this.y * invZ2 * invZ); return new Point(x, y); } } // Stores precomputed values for points.
JavaScript
class Point { // Base point aka generator // public_key = Point.BASE * private_key // Identity point aka point at infinity // point = point + zero_point // We calculate precomputes for elliptic curve point multiplication // using windowed method. This specifies window size and // stores precomputed values. Usually only base point would be precomputed. constructor(x, y) { this.x = x; this.y = y; this._WINDOW_SIZE = void 0; } // "Private method", don't use it directly _setWindowSize(windowSize) { this._WINDOW_SIZE = windowSize; pointPrecomputes.delete(this); } // Supports compressed Schnorr (32-byte) and ECDSA (33-byte) points static fromCompressedHex(bytes) { const isShort = bytes.length === 32; const x = bytesToNumber(isShort ? bytes : bytes.slice(1)); const y2 = weistrass(x); // y² = x³ + ax + b let y = sqrtMod(y2); // y = y² ^ (p+1)/4 const isYOdd = (y & _1n$1) === _1n$1; if (isShort) { // Schnorr if (isYOdd) y = mod(-y); } else { // ECDSA const isFirstByteOdd = (bytes[0] & 1) === 1; if (isFirstByteOdd !== isYOdd) y = mod(-y); } const point = new Point(x, y); point.assertValidity(); return point; } // Schnorr doesn't support uncompressed points, so this is only for ECDSA static fromUncompressedHex(bytes) { const x = bytesToNumber(bytes.slice(1, 33)); const y = bytesToNumber(bytes.slice(33)); const point = new Point(x, y); point.assertValidity(); return point; } // Converts hash string or Uint8Array to Point. static fromHex(hex) { const bytes = ensureBytes(hex); const header = bytes[0]; if (bytes.length === 32 || bytes.length === 33 && (header === 0x02 || header === 0x03)) { return this.fromCompressedHex(bytes); } if (bytes.length === 65 && header === 0x04) return this.fromUncompressedHex(bytes); throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${bytes.length}`); } // Multiplies generator point by privateKey. static fromPrivateKey(privateKey) { return Point.BASE.multiply(normalizePrivateKey(privateKey)); } // Recovers public key from ECDSA signature. // https://crypto.stackexchange.com/questions/60218 // Uses following formula: // Q = (r ** -1)(sP - hG) static fromSignature(msgHash, signature, recovery) { let h = msgHash instanceof Uint8Array ? bytesToNumber(msgHash) : hexToNumber(msgHash); const sig = normalizeSignature(signature); const { r, s } = sig; if (recovery !== 0 && recovery !== 1) { throw new Error('Cannot recover signature: invalid yParity bit'); } const prefix = 2 + (recovery & 1); const P_ = Point.fromHex(`0${prefix}${pad64(r)}`); const sP = JacobianPoint.fromAffine(P_).multiplyUnsafe(s); const hG = JacobianPoint.BASE.multiply(h); const rinv = invert(r, CURVE.n); const Q = sP.subtract(hG).multiplyUnsafe(rinv); const point = Q.toAffine(); point.assertValidity(); return point; } toRawBytes(isCompressed = false) { return hexToBytes(this.toHex(isCompressed)); } toHex(isCompressed = false) { const x = pad64(this.x); if (isCompressed) { return `${this.y & _1n$1 ? '03' : '02'}${x}`; } else { return `04${x}${pad64(this.y)}`; } } // Schnorr-related function toHexX() { return this.toHex(true).slice(2); } toRawX() { return this.toRawBytes(true).slice(1); } // A point on curve is valid if it conforms to equation. assertValidity() { const msg = 'Point is not on elliptic curve'; const { P } = CURVE; const { x, y } = this; if (x === _0n$1 || y === _0n$1 || x >= P || y >= P) throw new Error(msg); const left = mod(y * y); const right = weistrass(x); if ((left - right) % P !== _0n$1) throw new Error(msg); } equals(other) { return this.x === other.x && this.y === other.y; } // Returns the same point with inverted `y` negate() { return new Point(this.x, mod(-this.y)); } // Adds point to itself double() { return JacobianPoint.fromAffine(this).double().toAffine(); } // Adds point to other point add(other) { return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine(); } // Subtracts other point from the point subtract(other) { return this.add(other.negate()); } multiply(scalar) { return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine(); } }
JavaScript
class MultilangUtils { static get LANGUAGES() { return [ { code: 'nb', name: "Norsk" }, { code: 'se', name: "Sápmi" }, ]; } static get COOKIE_NAME() { return 'lang'; } static languagesExcept(language) { return MultilangUtils.LANGUAGES.filter(lang => lang.code !== language); } static languagesMap() { return MultilangUtils.LANGUAGES.reduce((obj, lang) => { obj[lang.code] = lang; return obj; }, {}); } static getParsedTooltipText(tooltipText) { return mmooc.menu.tooltipRegexpPattern.exec(tooltipText); } static makeSpansForTooltip(attrSelector) { var node = document.querySelector(attrSelector); var tooltip = node && node.getAttribute("data-html-tooltip-title"); if(tooltip) { var tooltipParsedResult = MultilangUtils.getParsedTooltipText(tooltip); if(tooltipParsedResult && tooltipParsedResult[1] && tooltipParsedResult[2]) { const spanned = MultilangUtils.getSpannedText(tooltipParsedResult[2]); if (spanned !== null) { var newTooltipText = mmooc.menu.createNewTooltipText(tooltip, tooltipParsedResult[1], spanned); //newTooltipText="<strong style='float:left'>Forrige modul:</strong> <br>ERLEND"; node.setAttribute("data-html-tooltip-title", newTooltipText); } } } } static makeSpansForSelectors(selectors) { selectors.map(selector => document.querySelectorAll(selector)) .flatMap(nodeList => Array.from(nodeList)) .forEach(node => { const spanned = MultilangUtils.makeSpansOf(node); if (spanned !== null) { node.innerHTML = spanned; } }); } static getSpannedText(textContent) { //Split the elements content with '|', then check each segment for language code and make <span>-elements. const splitArray = textContent.split("|"); let newContent = ''; for (let i = 0; i < splitArray.length; i++) { let match = /^\s*(\w\w)\s*:(.*)/.exec(splitArray[i]); //match language codes formed with two letters and a colon (no:, en: etc) if (match) { newContent += `<span class='language' lang='${match[1]}'>${match[2]}</span>`; } else { newContent += splitArray[i]; } } return newContent; //HTML-string with span-tags } static makeSpansOf(element) { // If there are child nodes that are not text nodes, abort. It should already be translated if (!Array.from(element.childNodes).every(childNode => childNode.nodeType === 3)) { return null; } return MultilangUtils.getSpannedText(element.textContent); } static getLanguageParameter() { const params = new URLSearchParams(location.search); return params.get(this.COOKIE_NAME); } static setLanguageParameter(languageCode) { if (!this.isValidLanguage(languageCode)) { return; } const params = new URLSearchParams(location.search); params.set(this.COOKIE_NAME, languageCode); window.history.replaceState({}, '', `${location.pathname}?${params}`); } static getLanguageCookie() { return document.cookie.replace(/(?:(?:^|.*;\s*)courselanguage\s*\=\s*([^;]*).*$)|^.*$/, "$1"); } static setLanguageCookie(languageCode) { if (!this.isValidLanguage(languageCode)) { return; } document.cookie = `courselanguage=${languageCode}; SameSite=Strict; path=/`; } static getLanguageCode() { const langCode = MultilangUtils.getLanguageParameter(); const langCookie = MultilangUtils.getLanguageCookie(); if (langCode) { return langCode; } else if (langCookie) { return langCookie; } else { return 'nb'; } } static getPreferredLanguage() { if(!mmooc.util.isMultilangCourse) { return mmooc.api.getLocale(); } if(MultilangUtils.getLanguageCode == "nb") { return mmooc.api.getLocale(); } return MultilangUtils.getLanguageCode(); } static setActiveLanguage(activeLang) { if (!this.isValidLanguage(activeLang)) { return; } MultilangUtils.setLanguageCookie(activeLang); MultilangUtils.setLanguageParameter(activeLang); const styleElement = document.getElementById('language-style'); styleElement.innerHTML = MultilangUtils.createCss(activeLang); } static isValidLanguage(languageCode) { return this.LANGUAGES.some(lang => lang.code === languageCode); } static createCss(activeLang) { return MultilangUtils.LANGUAGES.map(l => { var displayValue = "none"; if(activeLang == "all") { displayValue = "unset"; } else { displayValue = activeLang.toLowerCase() === l.code ? 'unset' : 'none'; } return `.language:lang(${l.code}) {display:${displayValue};}` }).join(" "); } static applyColorCodingInEditor() { function doApply() { const iframe = document.getElementById('wiki_page_body_ifr'); if (iframe !== null) { const doc = iframe.contentWindow.document; const editorCss = doc.createElement('style'); editorCss.innerHTML = ` .language:lang(se) { background-color: LIGHTCYAN; } .language:lang(nb) { background-color: MISTYROSE; }`; doc.head.appendChild(editorCss); } else { setTimeout(MultilangUtils.applyColorCodingInEditor, 500); } } doApply(); } static initializeCss(language) { const styleElement = document.createElement('style'); styleElement.id = 'language-style'; styleElement.innerHTML = MultilangUtils.createCss(language); document.head.appendChild(styleElement); } static makeSpansOnPage() { const selectors = [ '.translate', 'div.tooltiptext', '.show-content.user_content h1.page-title', 'a.mmooc-module-name', '.discussion-title', ]; if (location.pathname.endsWith('/modules')) { selectors.push( 'a.title', 'span.name', 'span.title', ); } MultilangUtils.makeSpansForSelectors(selectors); } }
JavaScript
class InstantSearchQueryCollector extends AbstractCollector { /** * Construct instant search collector * * @constructor * @param {string} selectorExpression - Document query selector identifying the elements to attach to */ constructor(selectorExpression, listenerType) { super("instant-search"); this.selectorExpression = selectorExpression; this.listenerType = listenerType; } /** * Add impression event listeners to the identified elements, write the data * when the event occurs * * @param {object} writer - The writer to send the data to */ attach(writer) { var type = this.getType(); let handler = (searchBox, e, writer) => { // Ignore shift, ctrl, etc. presses, react only on characters if (e.which === 0) { return; } // Delay the reaction of the event, clean the timeout if the event fires // again and start counting from 0 delay(function() { var keywords = searchBox.value; if (keywords && keywords.length >= MIN_LENGTH) { writer.write({ "type" : type, "keywords" : keywords }); } }, DELAY); } // The Sentiel library uses animationstart event listeners which may interfere with // animations attached on elemenets. The in-library provided workaround mechanism does not work // 100%, thus we provide the listenerType choice below. The tradeoffs // "dom" - no animation interference, only onclick attached, but does not handle elements inserted in the DOM later // "sentinel (default)" - works on elements inserted in the DOM anytime, but interferes with CSS animations on these elements if (this.listenerType == "dom") { var nodeList = this.getDocument().querySelectorAll(this.selectorExpression); nodeList.forEach(el => el.addEventListener("keypress", ev => handler(el, ev, writer))); } else { var sentinel = new Sentinel(this.getDocument()); sentinel.on(this.selectorExpression, el => el.addEventListener("keypress", ev => handler(el, ev, writer))); } } }
JavaScript
class ExceptionText { /** @return {string} */ static notImplemented() { return 'SecurityException: Not implemented yet.'; } /** @return {string} */ static nullKeyset() { return 'SecurityException: Serialized keyset has to be non-null.'; } /** @return {string} */ static invalidSerialization() { return 'SecurityException: Could not parse the given serialized proto as ' + 'a keyset proto.'; } }
JavaScript
class MySet { constructor(args) { this.data = {} if (!args) return for (const str of args) { this.data[str] = true } } add(str) { this.data[str] = true } has(str) { return this.data[str] } remove(str) { delete this.data[str] } }
JavaScript
class AppleConnect extends ConnectBase { /** * Constructor for apple connect. * * @param {object} params * @param {string} params.authorization_code * @param {string} params.identity_token * @param {string} params.apple_user_id * @param {string} params.full_name * @param {Boolean} params.dev_login * * @augments ServiceBase * * @constructor */ constructor(params) { super(params); const oThis = this; oThis.authorizationCode = params.authorization_code; oThis.identityToken = params.identity_token; oThis.appleId = params.apple_user_id; oThis.duplicateRequestIdentifier = oThis.appleId; oThis.fullName = params.full_name; oThis.isDevLogin = params.dev_login; oThis.appleOAuthDetails = null; oThis.decryptedAppleEmail = null; oThis.appleClientId = null; oThis.appleRedirectUri = null; } /** * Method to validate access tokens and fetching data from Social platforms. * * @returns {Promise<void>} * @private */ async _validateAndFetchSocialInfo() { const oThis = this; logger.log('FullName: ', oThis.fullName); oThis.appleRedirectUri = basicHelper.getLoginRedirectUrl( oThis.isDevLogin, socialConnectServiceTypeConstants.appleSocialConnect ); // Different client id has to be used for app and web requests. if (apiSourceConstants.isWebRequest(oThis.apiSource)) { oThis.appleClientId = coreConstants.PA_APPLE_WEB_SERVICE_ID; } else { oThis.appleClientId = coreConstants.PA_APPLE_CLIENT_ID; } // let promiseArray = []; // promiseArray.push(oThis.verifyIdentityToken()); // promiseArray.push(oThis.getAccessTokenFromApple()); await oThis.getAccessTokenFromApple(); await oThis.verifyIdentityToken(); // await Promise.all(promiseArray); } /** * Verify identity token * * @returns {Promise<void>} */ async verifyIdentityToken() { const oThis = this; let publicKeys = await new GetApplePublicKey().perform(), decryptedIdentityToken = await appleHelper.getDecryptedIdentityToken(oThis.identityToken, publicKeys); if (decryptedIdentityToken.iss !== APPLE_API_URL) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_c_l_ba_1', api_error_identifier: 'something_went_wrong', debug_options: { Error: `id token not issued by correct OpenID provider - expected: ${APPLE_API_URL} | from: ${ decryptedIdentityToken.iss }` } }) ); } if (decryptedIdentityToken.exp < Date.now() / 1000) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_c_l_ba_3', api_error_identifier: 'something_went_wrong', debug_options: { Error: `id token has expired` } }) ); } if (decryptedIdentityToken.email) { oThis.decryptedAppleEmail = decryptedIdentityToken.email; } // In case of web request, we are not getting apple id in response if (apiSourceConstants.isWebRequest(oThis.apiSource)) { oThis.appleId = decryptedIdentityToken.sub; } if (decryptedIdentityToken.aud !== oThis.appleClientId) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'l_c_l_ba_2', api_error_identifier: 'something_went_wrong', debug_options: { Error: `aud parameter does not include this client - is: ${decryptedIdentityToken.aud} | expected: ${ oThis.appleClientId }` } }) ); } } /** * Get access token from apple * * @returns {Promise<void>} */ async getAccessTokenFromApple() { const oThis = this; let clientSecret = appleHelper.createClientSecret(oThis.appleClientId), oAuthDetails = await new GetAccessToken({ clientSecret: clientSecret, authorizationCode: oThis.authorizationCode, appleClientId: oThis.appleClientId, appleRedirectUri: oThis.appleRedirectUri }).perform(); if (oAuthDetails.error) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_c_a_1', api_error_identifier: 'something_went_wrong', debug_options: {} }) ); } oThis.appleOAuthDetails = oAuthDetails; console.log('appleOAuthDetails: ', oThis.appleOAuthDetails); } /** * Method to fetch data from respective social_users tables * * @Sets oThis.socialUserObj * @returns {Promise<void>} * @private */ async _fetchSocialUser() { const oThis = this; //fetch social user on the basis of apple id let queryResponse = await new AppleUserModel() .select('*') .where(['apple_id = ?', oThis.appleId]) .fire(); if (queryResponse.length > 0) { oThis.socialUserObj = new AppleUserModel().formatDbData(queryResponse[0]); } } /** * Method to check whether same social platform is connected before. * * @param userObj * @private */ _sameSocialConnectUsed(userObj) { // Look for property set in user object. const propertiesArray = new UserModel().getBitwiseArray('properties', userObj.properties); return propertiesArray.indexOf(userConstants.hasAppleLoginProperty) > -1; } /** * Method to perform signup action * * @returns {Promise<void>} * @private */ async _performSignUp() { const oThis = this; let params = { appleOAuthDetails: oThis.appleOAuthDetails, appleUserEntity: oThis._getAppleFormattedData(), appleUserObj: oThis.socialUserObj, headers: oThis.headers }; Object.assign(params, oThis._appendCommonSignupParams()); oThis.serviceResp = await new AppleSignup(params).perform(); } /** * Method to perform login action * * @returns {Promise<void>} * @private */ async _performLogin() { const oThis = this; let params = { appleUserObj: oThis.socialUserObj, appleUserEntity: oThis._getAppleFormattedData(), accessToken: oThis.appleOAuthDetails.access_token, refreshToken: oThis.appleOAuthDetails.refresh_token, isNewSocialConnect: oThis.newSocialConnect, userId: oThis.userId, apiSource: oThis.apiSource }; oThis.serviceResp = await new AppleLogin(params).perform(); } /** * Get unique property from github info, like email * * @returns {{}|{kind: string, value: *}} * @private */ _getSocialUserUniqueProperties() { const oThis = this; if (!oThis.decryptedAppleEmail || !CommonValidators.isValidEmail(oThis.decryptedAppleEmail)) { return {}; } return { kind: userIdentifierConstants.emailKind, values: [oThis.decryptedAppleEmail] }; } /** * Get Formatted data for Apple * * @returns {{fullName: *, socialUserName: *, id: *, email: *}} * @private */ _getAppleFormattedData() { const oThis = this; let formattedAppleName = new AppleNameFormatter({ fullName: oThis.fullName, email: oThis.decryptedAppleEmail }); let appleUserEntity = { id: oThis.appleId, email: oThis.decryptedAppleEmail, fullName: formattedAppleName.formattedName, socialUserName: formattedAppleName.socialUserName }; return appleUserEntity; } /** * Store user data for future reference, * Like in case of Apple connect, user data can only be retrieved first time. * This method is overridden only for apple. * * @returns {Promise<void>} * @private */ async _storeUserDataForFutureRef() { const oThis = this; const appleUserEntity = oThis._getAppleFormattedData(), insertParams = { apple_id: appleUserEntity.id, name: appleUserEntity.fullName, email: appleUserEntity.email }; // If Apple user obj is already present, then do nothing // As no data can be updated if (!oThis.socialUserObj) { await new AppleUserModel().insert(insertParams).fire(); } } }
JavaScript
class Runner { /** * @param {Felony} felony */ constructor(felony) { /** * Array of loaded cron jobs * * @type {Array<typeof Cron>} */ this._crons = []; /** * List of crons loaded and ready to run. * * @type {object[typeof Cron]} */ this.crons = {}; this.felony = felony; } /** * Load all the available jobs onto the worker. * * @return {Promise<void>} */ async load() { const jobs = await this.felony.kernel.readRecursive(path.resolve(this.felony.appRootPath, "crons")); for (const job of jobs) { const Imported = (await import(job)).default; let replacePath = `${path.resolve(this.felony.appRootPath, "crons")}/`; // we need to adjust the path depending on operating system if (job.startsWith("file://")) { replacePath = `file://${path.resolve(this.felony.appRootPath, "crons")}/`; } Imported.__path = job.replace(replacePath, ""); if (Imported.__kind === "Cron" && Imported.active) { this._crons.push(Imported); } } } /** * Run the crons if arguments allow it * * @return {Promise<any>} */ async run() { if (!this.felony.arguments.cron) { return; } await this.load(); for (const Job of this._crons) { const job = new Job(); this.crons[Job.__path] = { job, cron: new CronJob(Job.schedule, async () => { try { await job.handle(); } catch (error) { this.felony.log.error(error); } }, null, true, "UTC"), }; } } }
JavaScript
class NotBetween extends Not { /** * Constructor. */ constructor() { super(new Between()); } }
JavaScript
class LogDNAStream extends EventEmitter { constructor(options) { super() this.logger = createLogger(options.key, { ...options , indexMeta: true , UserAgent: `${pkg.name}/${pkg.version}` }) this.logger.on('error', (err) => { this.emit('error', err) }) } async write(record) { const { msg: message , level , name: app , hostname , timestamp // Bunyan provides timestamp, so just use that for LogDNA's time as well , ...meta } = record for (const [key, value] of Object.entries(meta)) { if (!value.then) continue; meta[key] = await value; } const opts = { level: levels[level] , app , meta: { ...meta , hostname } , timestamp } this.logger.log(message, opts) }; }
JavaScript
class DirectiveView extends DecoratorView { constructor(options = {}) { super(options); }; render() { return super.render(); }; remove() { this.removeTemplate(this.el, true); return super.remove(); }; }
JavaScript
class ProductThumbnail extends React.Component { render() { const { product, ...props } = this.props const color = `rsfProduct${product.id}.color` return ( <Image {...props} src={product.color.selected.thumbnail || product.thumbnail} amp-bind={`src=>${color}.selected.thumbnail || "${product.thumbnail}"`} /> ) } }
JavaScript
class MongoAdapter extends AbstractNosqlAdapter{ validateConfig(config){ if(!config['db']['url']) throw Error('db.url must be set up in config'); } constructor(app_config){ super(app_config); this.config = app_config; this.db = null; this.validateConfig(this.config); logger.debug('Mongo module initialized!'); } /** * Close the nosql database connection - abstract to the driver */ close(){ this.db.close(); } /** * Update single document in database * @param {object} item document to be updated in database */ updateDocument(collectionName, item) { this.db.collection(collectionName).findAndModify( this.getWhereQuery(item), // query [['_id','asc']], // sort order {$set: item }, // replacement, replaces only the field "hi" TODO: Apply the very same format ElasticSearch module have { upsert: true }, // options function(err, object) { if (err){ logger.warn(err.message); // returns error if no matching object found } }); } /** * Remove records other than <record>.tsk = "transactionKey" * @param {String} collectionName * @param {int} transactionKey transaction key - which is usualy a timestamp */ cleanupByTransactionkey(collectionName, transactionKey){ this.db.collection(collectionName).remove({tsk: transactionKey},function(err, obj) { if (err) throw err; logger.info(obj.result.n + " document(s) deleted"); }); } /** * Update multiple documents in database * @param {array} items to be updated */ updateDocumentBulk(collectionName, items) { for (let doc of items) { this.updateDocument(collectionName, doc); // TODO: use native Mongodb bulk update's support } } /** * Connect / prepare driver * @param {Function} done callback to be called after connection is established */ connect (done){ MongoClient.connect(this.config.db.url, (err, db) => { done(db); }); } }
JavaScript
class NullableStringSchemaType extends StringSchema { constructor() { super() const self = this self.withMutation(function() { self .transform(function(value) { if (self.isType(value) && Boolean(value)) { return value } return null }) .nullable(true) }) } }
JavaScript
class HSplitter extends React.Component { constructor(props) { super(props); this.splitterDrag = this.splitterDrag.bind(this); } componentDidMount() { this.box = document.getElementById(this.props.boxId); this.boxWindow = document.getElementById(this.props.boxWindowId); // slice removes "px" from width this.boxDefaultWidth = +window .getComputedStyle(this.box) .getPropertyValue("width") .slice(0, -2); this.splitter.addEventListener("mousedown", e => { if (e.which === 1) { document.getElementById("content").style.pointerEvents = "none"; this.prevX = e.clientX; this.boxWindow.addEventListener("mousemove", this.splitterDrag); document.body.classList.add("splitter-cursor"); e.preventDefault(); } }); } componentWillUnmount() { document.getElementById("content").style.pointerEvents = "all"; document.body.classList.remove("splitter-cursor"); document .getElementById("dialog-content-box") .removeEventListener("mousemove", this.splitterDrag); } isMouseButtonDown(e) { if (e.buttons === null) { return e.which !== 0; } else { return e.buttons !== 0; } } splitterDrag(e) { if (this.isMouseButtonDown(e)) { const disp = e.clientX - this.prevX; const newWidth = Math.max(this.boxDefaultWidth, this.box.offsetWidth + disp); this.box.style.width = `${newWidth}px`; this.prevX = Math.max( this.box.getBoundingClientRect().left + this.boxDefaultWidth, e.clientX ); } else { document.getElementById("content").style.pointerEvents = "all"; this.boxWindow.removeEventListener("mousemove", this.splitterDrag); document.body.classList.remove("splitter-cursor"); } } render() { return <div className="splitter vertical" ref={node => (this.splitter = node)} />; } }
JavaScript
class Link { constructor(uri, params) { this.uri = uri; this.params = params; } get rel() { return this.params['rel']; } static parse(value) { const parts = value.split(/;\s*/, 2); const uri = parts[0].trim().replace(/^</, '').replace(/>$/, ''); const params = {} parts.slice(1).map(x => x.split('=', 2)).filter(x => x.length === 2) .forEach(x => params[x[0]] = x[1].replace(/^"/, '').replace(/"$/, '')); return new Link(uri, params); } }
JavaScript
class TestSuite { constructor(spec) { this.spec = spec; } run() { Reflect.ownKeys(Reflect.getPrototypeOf(this)) .filter(name => name !== 'constructor') .forEach(name => this[name]()); } report(id, status, message) { const item = this.spec[id]; if (item) { const data = { id: id, label: item.label, level: item.requirementLevel, status: TestSuite.statusClass(status), description: item.statement, message: message, uri: item.requirementReference }; window.top.postMessage(data, window.location.origin); } else { throw `Invalid identifier: [${id}]`; } } static statusClass(status) { switch(status) { case true: return 'pass'; case false: return 'fail'; default: return 'skip'; } } }
JavaScript
class IDTokenSuite extends TestSuite { constructor(spec, clientId, issuer, token) { super(spec); this.clientId = clientId; this.issuer = issuer; this.token = token; } tokenType() { this.report('TokenType', this.token.token_type === 'DPoP', 'Verify that the token_type value equals "DPoP".'); } tokenIdIssuer() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenIssuerClaim', idToken.body.iss === this.issuer, 'Verify that the token "iss" claim equals the "issuer" field in the server metadata.'); } tokenValidation() { JOSE.validate(this.token.id_token).then(status => this.report('IdTokenValidation', status, 'Verify that the token passes JWT validation.')); } tokenAudienceClientId() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenAudienceClaim', idToken.body.aud?.includes(this.clientId), 'Verify that the "aud" claim includes the client identifier.'); } tokenAudienceSolid() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenAudienceClaimSolid', idToken.body.aud?.includes("solid"), 'Verify that the "aud" claim includes the string "solid".'); } tokenAuthorizedParty() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenAuthorizedPartyClaim', idToken.body.azp === this.clientId, 'Verify that the "azp" claim equals the client identifier.'); } tokenWebId() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenWebidClaim', idToken.body.webid?.startsWith('https://'), 'Verify that the "webid" claim is present in the ID Token.'); } tokenDerefWebIdHeaders() { const idToken = JOSE.parse(this.token.id_token); fetch(idToken.body.webid).then(res => res.headers.get('Link')).then(links => this.report('WebidHeaderDiscovery', links?.split(/,\s*(?:<)/).map(l => Link.parse(l)) .filter(l => l.rel === 'http://www.w3.org/ns/solid/terms#oidcIssuer') .map(l => l.uri).includes(idToken.body.iss), `Verify that the solid:oidcIssuer relation is present in the response link headers: [${links || 'n/a'}].`)); } tokenIatClaim() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenIatClaim', idToken.body.iat < Date.now() / 1000 + 60, `Verify that the "iat" value is not in the future: ${idToken.body.iat}.`); } tokenExpClaim() { const idToken = JOSE.parse(this.token.id_token); this.report('IdTokenExpClaim', idToken.body.exp > Date.now() / 1000, `Verify that the 'exp' value is not in the past: ${idToken.body.exp}.`); } }
JavaScript
class DiscoverySuite extends TestSuite { constructor(spec, metadata) { super(spec); this.metadata = metadata; } discoveryIssuer() { this.report('MetadataIssuer', this.metadata.issuer?.startsWith('http'), 'Verify that the "issuer" field is present.'); } discoveryClaimSupport() { this.report('MetadataWebidClaim', this.metadata.claims_supported?.includes('webid'), 'Verify that "webid" is included in the "claims_supported" field.'); } discoveryPkceSupport() { this.report('MetadataProofKeyCodeExchange', this.metadata.code_challenge_methods_supported?.includes('S256'), 'Verify that the "S256" algorithm is included in the "code_challenge_methods_supported" field.'); } discoveryGrantTypeSupport() { this.report('MetadataAuthorizationCodeGrant', this.metadata.grant_types_supported?.includes('authorization_code'), 'Verify that the "authorization_code" flow is included in the "grant_types_supported" field.'); } discoveryDpopSupport() { this.report('MetadataDpopAlgorithm', this.metadata.dpop_signing_alg_values_supported?.some(alg => ['ES256', 'RS256'].includes(alg)), 'Verify that the "dpop_signing_alg_values_supported" field includes either "ES256" or "RS256".'); } discoverySigningAlgSupport() { this.report('MetadataSigningAlgorithm', this.metadata.id_token_signing_alg_values_supported?.includes('RS256'), 'Verify that the "RS256" algorithm is included in the "id_token_signing_alg_values_supported" field.'); } discoveryDynamicRegistrationSupport() { this.report('MetadataDynamicRegistration', this.metadata.registration_endpoint != null, 'Verify whether dynamic client registration is supported.'); } discoveryLogoutSupport() { this.report('MetadataLogout', this.metadata.end_session_endpoint != null, 'Verify whether client-initiated logout is supported.'); } discoveryTokenEndpoint() { this.report('MetadataTokenEndpoint', this.metadata.token_endpoint != null, 'Verify that the token_endpoint field is present'); } discoveryAuthorizationEndpoint() { this.report('MetadataAuthorizationEndpoint', this.metadata.authorization_endpoint != null, 'Verify that the authorization_endpoint field is present'); } discoveryJwksEndpoint() { this.report('MetadataJwksEndpoint', this.metadata.jwks_uri != null, 'Verify that the jwks_uri field is present'); } discoverySubjectTypesSupported() { this.report('MetadataSubjectTypesSupported', this.metadata.subject_types_supported != null, 'Verify whether the supported Subject Identifier types are listed'); } discoveryResponseTypeSupport() { this.report('MetadataResponseType', this.metadata.response_types_supported?.includes('code'), 'Verify that the "code" response is included in the "response_types_supported" field.'); } discoveryScopeSupport() { this.report('MetadataWebidScope', this.metadata.scopes_supported?.includes('webid'), 'Verity that the "webid" scope is included in the "scopes_supported" field'); } }
JavaScript
class OrbitalControls extends ControlsBase { /** * Creates an instance of OrbitalControls. * @param {Renderer} renderer An instance of a Lore renderer. * @param {Number} radius The distance of the camera to the lookat vector. * @param {Vector3f} lookAt The lookat vector. */ constructor(renderer, radius, lookAt = new Vector3f(0.0, 0.0, 0.0)) { super(renderer, lookAt); this.up = Vector3f.up(); this.radius = radius; this.yRotationLimit = Math.PI; this._dPhi = 0.0; this._dTheta = 0.0; this._dPan = new Vector3f(0.0, 0.0, 0.0); this.spherical = new SphericalCoords(); this.scale = 0.95; this.camera.position = new Vector3f(radius, radius, radius); this.camera.updateProjectionMatrix(); this.camera.updateViewMatrix(); this.rotationLocked = false; let that = this; this.addEventListener("mousedrag", function (e) { that.update(e.e, e.source); }); this.addEventListener("touch", function (e) { that.update(e.e, e.source); }); this.addEventListener("mousewheel", function (e) { that.update( { x: 0, y: -e.e }, "wheel" ); }); // Initial update this.update( { x: 0, y: 0 }, "left" ); } /** * Limit the vertical rotation to the horizon (the upper hemisphere). * * @param {Boolean} limit A boolean indicating whether or not to limit the vertical rotation to the horizon. * @returns {OrbitalControls} Returns itself. */ limitRotationToHorizon(limit) { if (limit) { this.yRotationLimit = 0.5 * Math.PI; } else { this.yRotationLimit = Math.PI; } return this; } /** * Sets the distance (radius of the sphere) from the lookat vector to the camera. * * @param {Number} radius The radius. * @returns {OrbitalControls} Returns itself. */ setRadius(radius) { this.radius = radius; this.camera.position = new Vector3f(0, 0, radius); this.camera.updateProjectionMatrix(); this.camera.updateViewMatrix(); this.update(); return this; } /** * Update the camera (on mouse move, touch drag, mousewheel scroll, ...). * * @param {*} [e=null] A mouse or touch events data. * @param {String} [source=null] The source of the input ('left', 'middle', 'right', 'wheel', ...). * @returns {OrbitalControls} Returns itself. */ update(e = null, source = null) { if (source == "left" && !this.rotationLocked) { // Rotate this._dTheta = (-2 * Math.PI * e.x) / (this.canvas.clientWidth * this.camera.zoom); this._dPhi = (-2 * Math.PI * e.y) / (this.canvas.clientHeight * this.camera.zoom); // It's just to fast like this ... // this._dTheta = -2 * Math.PI * e.x / this.canvas.clientWidth; // this._dPhi = -2 * Math.PI * e.y / this.canvas.clientHeight; } else if (source == "right" || (source == "left" && this.rotationLocked)) { // Translate let x = (e.x * (this.camera.right - this.camera.left)) / this.camera.zoom / this.canvas.clientWidth; let y = (e.y * (this.camera.top - this.camera.bottom)) / this.camera.zoom / this.canvas.clientHeight; let u = this.camera.getUpVector().components; let r = this.camera.getRightVector().components; this._dPan.components[0] = r[0] * -x + u[0] * y; this._dPan.components[1] = r[1] * -x + u[1] * y; this._dPan.components[2] = r[2] * -x + u[2] * y; } else if (source == "middle" || source == "wheel" || source == "pinch") { if (e.y > 0) { // Zoom Out this.camera.zoom = Math.max(0, this.camera.zoom * this.scale); this.camera.updateProjectionMatrix(); this.raiseEvent("zoomchanged", this.camera.zoom); } else if (e.y < 0) { // Zoom In this.camera.zoom = Math.max(0, this.camera.zoom / this.scale); this.camera.updateProjectionMatrix(); this.raiseEvent("zoomchanged", this.camera.zoom); } } // Update the camera let offset = this.camera.position.clone().subtract(this.lookAt); this.spherical.setFromVector(offset); this.spherical.components[1] += this._dPhi; this.spherical.components[2] += this._dTheta; this.spherical.limit(0, this.yRotationLimit, -Infinity, Infinity); this.spherical.secure(); // Limit radius here this.lookAt.add(this._dPan); offset.setFromSphericalCoords(this.spherical); this.camera.position.copyFrom(this.lookAt).add(offset); this.camera.setLookAt(this.lookAt); this.camera.updateViewMatrix(); this._dPhi = 0.0; this._dTheta = 0.0; this._dPan.set(0, 0, 0); this.raiseEvent("updated"); return this; } /** * Sets the lookat vector, which is the center of the orbital camera sphere. * * @param {Vector3f} lookAt The lookat vector. * @returns {ControlsBase} Returns itself. */ setLookAt(lookAt) { // TODO: Most of this code (except for setting lookAt to lookAt instead of _dPan) // is compied from updated. Maybe fix that // Update the camera let offset = this.camera.position.clone().subtract(this.lookAt); this.spherical.setFromVector(offset); this.spherical.components[1] += this._dPhi; this.spherical.components[2] += this._dTheta; this.spherical.limit(0, this.yRotationLimit, -Infinity, Infinity); this.spherical.secure(); // Limit radius here this.lookAt = lookAt.clone(); offset.setFromSphericalCoords(this.spherical); this.camera.position.copyFrom(this.lookAt).add(offset); this.camera.setLookAt(this.lookAt); this.camera.updateViewMatrix(); this.raiseEvent("updated"); return this; } /** * Moves the camera around the sphere by spherical coordinates. * * @param {Number} phi The phi component of the spherical coordinates. * @param {Number} theta The theta component of the spherical coordinates. * @returns {OrbitalControls} Returns itself. */ setView(phi, theta) { let offset = this.camera.position.clone().subtract(this.lookAt); this.spherical.setFromVector(offset); this.spherical.components[1] = phi; this.spherical.components[2] = theta; this.spherical.secure(); offset.setFromSphericalCoords(this.spherical); this.camera.position.copyFrom(this.lookAt).add(offset); this.camera.setLookAt(this.lookAt); this.camera.updateViewMatrix(); this.raiseEvent("updated"); return this; } /** * Zoom in on the lookat vector. * * @returns {OrbitalControls} Returns itself. */ zoomIn() { this.camera.zoom = Math.max(0, this.camera.zoom / this.scale); this.camera.updateProjectionMatrix(); this.raiseEvent("zoomchanged", this.camera.zoom); this.raiseEvent("updated"); return this; } /** * Zoom out from the lookat vector. * * @returns {OrbitalControls} Returns itself. */ zoomOut() { this.camera.zoom = Math.max(0, this.camera.zoom * this.scale); this.camera.updateProjectionMatrix(); this.raiseEvent("zoomchanged", this.camera.zoom); this.raiseEvent("updated"); return this; } /** * Set the zoom to a given value. * * @param {Number} zoom The zoom value. * @returns {OrbitalControls} Returns itself. */ setZoom(zoom) { this.camera.zoom = zoom; this.camera.updateProjectionMatrix(); this.raiseEvent("zoomchanged", this.camera.zoom); this.update(); return this; } /** * Get the zoom. * * @returns {Number} The zoom value. */ getZoom() { return this.camera.zoom; } /** * Set zoom so it contains a bounding box * * @param {Number} width The width of the square to be contained. * @param {Number} height The height of the square to be contained. * @param {Number} padding Padding applied to the zoom as a fraction of width and height. * @returns {OrbitalControls} Returns itself. */ zoomTo(width, height, padding = 0.0) { if (this.camera.type !== 'Lore.OrthographicCamera') { throw ('Feature not implemented.'); } this.setZoom(this.camera.getRequiredZoomToContain( width, height, padding )); return this; } /** * * @param {Vector3f} v The vector to pan to. * @returns {OrbitalControls} Returns itself. */ panTo(v) { return this; } /** * Sets the view by name (left, right, top, bottom, back, front, free) * * @param {String} viewName The name of the view. * * @returns {OrbitalControls} Returns itself. */ setViewByName(viewName) { switch (viewName) { case "left": this.setLeftView(); break; case "right": this.setRightView(); break; case "top": this.setTopView(); break; case "bottom": this.setBottomView(); break; case "back": this.setBackView(); break; case "front": this.setFrontView(); break; default: this.setFreeView(); } return this; } /** * Set the camera to the top view (locks rotation). * * @returns {OrbitalControls} Returns itself. */ setTopView() { this.setView(0.0, 2.0 * Math.PI); this.rotationLocked = true; return this; } /** * Set the camera to the bottom view (locks rotation). * * @returns {OrbitalControls} Returns itself. */ setBottomView() { this.setView(0.0, 0.0); this.rotationLocked = true; return this; } /** * Set the camera to the right view (locks rotation). * * @returns {OrbitalControls} Returns itself. */ setRightView() { this.setView(0.5 * Math.PI, 0.5 * Math.PI); this.rotationLocked = true; return this; } /** * Set the camera to the left view (locks rotation). * * @returns {OrbitalControls} Returns itself. */ setLeftView() { this.setView(0.5 * Math.PI, -0.5 * Math.PI); this.rotationLocked = true; return this; } /** * Set the camera to the front view (locks rotation). * * @returns {OrbitalControls} Returns itself. */ setFrontView() { this.setView(0.5 * Math.PI, 2.0 * Math.PI); this.rotationLocked = true; return this; } /** * Set the camera to the back view (locks rotation). * * @returns {OrbitalControls} Returns itself. */ setBackView() { this.setView(0.5 * Math.PI, Math.PI); this.rotationLocked = true; return this; } /** * Set the camera to free view (unlocks rotation). * * @returns {OrbitalControls} Returns itself. */ setFreeView() { this.setView(0.25 * Math.PI, 0.25 * Math.PI); this.rotationLocked = false; return this; } }
JavaScript
class ComponentPortal { constructor(component, injector) { this.component = component; this.injector = injector; } /** Attach this portal to a host. */ attach(host, newestOnTop) { this._attachedHost = host; return host.attach(this, newestOnTop); } /** Detach this portal from its host */ detach() { const host = this._attachedHost; if (host) { this._attachedHost = undefined; return host.detach(); } } /** Whether this portal is attached to a host. */ get isAttached() { return this._attachedHost != null; } /** * Sets the PortalHost reference without performing `attach()`. This is used directly by * the PortalHost when it is performing an `attach()` or `detach()`. */ setAttachedHost(host) { this._attachedHost = host; } }
JavaScript
class BasePortalHost { attach(portal, newestOnTop) { this._attachedPortal = portal; return this.attachComponentPortal(portal, newestOnTop); } detach() { if (this._attachedPortal) { this._attachedPortal.setAttachedHost(); } this._attachedPortal = undefined; if (this._disposeFn) { this._disposeFn(); this._disposeFn = undefined; } } setDisposeFn(fn) { this._disposeFn = fn; } }