public KmeansInput(Array samples, MatrixType samplesType, int nClusters, CvTermCriteria criteria) { Samples = samples; SamplesType = samplesType; NClusters = nClusters; Criteria = criteria; }
public SerializableCvMat(CvMat mat) { this.Cols = mat.Cols; this.Rows = mat.Rows; this.ElemType = mat.ElemType; this.Array = mat.ToArray(); }
protected Expression Visit(BinaryExpression expression) { // First, dispatch to resolve type of node at deeper level Visit((Node)expression); var leftType = expression.Left.TypeInference.TargetType; var rightType = expression.Right.TypeInference.TargetType; var returnType = expression.TypeInference.ExpectedType ?? expression.TypeInference.TargetType; bool isNumericOperator = true; switch (expression.Operator) { case BinaryOperator.LogicalAnd: case BinaryOperator.LogicalOr: isNumericOperator = false; returnType = GetBinaryImplicitConversionType(expression.Span, leftType, rightType, true); expression.TypeInference.TargetType = returnType; break; case BinaryOperator.Less: case BinaryOperator.LessEqual: case BinaryOperator.Greater: case BinaryOperator.GreaterEqual: case BinaryOperator.Equality: case BinaryOperator.Inequality: isNumericOperator = false; returnType = GetBinaryImplicitConversionType(expression.Span, leftType, rightType, false); TypeBase resultType = ScalarType.Bool; if (returnType is VectorType) { resultType = new VectorType(ScalarType.Bool, ((VectorType)returnType).Dimension); } else if (returnType is MatrixType) { var matrixType = (MatrixType)returnType; resultType = new MatrixType(ScalarType.Bool, matrixType.RowCount, matrixType.ColumnCount); } expression.TypeInference.TargetType = resultType; break; } if (returnType != null) { if (returnType == ScalarType.Bool && isNumericOperator) { var typeToCheck = leftType ?? rightType; if (typeToCheck != null) return ConvertExpressionToBool(expression, typeToCheck); } } if (!isNumericOperator || CastHelper.NeedConvertForBinary(leftType, returnType)) expression.Left = Cast(leftType, returnType, expression.Left); if (!isNumericOperator || CastHelper.NeedConvertForBinary(rightType, returnType)) expression.Right = Cast(rightType, returnType, expression.Right); return expression; }
/// <summary> /// Construct a rotation matrix,origin at (0,0,0) /// </summary> /// <param name="xAxis">identity of x axis</param> /// <param name="yAxis">identity of y axis</param> /// <param name="zAxis">identity of z axis</param> public Matrix4(Vector4 xAxis,Vector4 yAxis, Vector4 zAxis) { m_type = MatrixType.Rotation; Identity(); m_matrix[0, 0] = xAxis.X; m_matrix[0, 1] = xAxis.Y; m_matrix[0, 2] = xAxis.Z; m_matrix[1, 0] = yAxis.X; m_matrix[1, 1] = yAxis.Y; m_matrix[1, 2] = yAxis.Z; m_matrix[2, 0] = zAxis.X; m_matrix[2, 1] = zAxis.Y; m_matrix[2, 2] = zAxis.Z; }
public static void ConvertMaps(Mat map1, Mat map2, Mat dstmap1, Mat dstmap2, MatrixType dstmap1type, bool nninterpolation = false) { if (map1 == null) throw new ArgumentNullException("map1"); if (map2 == null) throw new ArgumentNullException("map2"); if (dstmap1 == null) throw new ArgumentNullException("dstmap1"); if (dstmap2 == null) throw new ArgumentNullException("dstmap2"); CppInvoke.cv_convertMaps(map1.CvPtr, map2.CvPtr, dstmap1.CvPtr, dstmap2.CvPtr, dstmap1type, nninterpolation); }
internal DoubleSubmatrix(Matrix<double> matrix, int rowOffset, int columnOffset, int rows, int columns) { if (typeof(Matrix_SDA).IsInstanceOfType(matrix)) mt = MatrixType.SDA; // дописать else mt = MatrixType.SDA; this.offsetRow = rowOffset; this.offsetColumn = columnOffset; this.rows = rows; this.columns = columns; this.parent = matrix; }
private static void PrintMatrix(int[,] matrix, MatrixType type) { Console.WriteLine(type + "\n"); for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write("{0, -4}", matrix[row, col]); } Console.WriteLine(); } Console.WriteLine(new String('_', matrix.GetLength(0) * 5)); }
internal AnimatableMatrix GetMatrix(MatrixType whichMatrix) { switch (whichMatrix) { case MatrixType.World: return World; case MatrixType.View: return View; case MatrixType.Projection: return Projection; } throw new InvalidOperationException(String.Format("Unrecognized matrix type: {0}", whichMatrix)); }
/// <summary> /// Extracts all of the 6 values from a Transformation Matrix /// </summary> /// <param name="path">The XML containing the Transformation Matrix</param> /// <param name="matrixType">The type of attribute to be extracted</param> /// <returns></returns> public static string[] GetMatrixValuesFromXml(XElement path, MatrixType matrixType) { string attribute; if (matrixType == MatrixType.PathMatrix) { attribute = "transform"; } else { attribute = "gradientTransform"; } string input = path.Attribute(attribute).Value; return input.Split('(', ')')[1].Split(' '); }
/// <summary> /// Constructs a matrix with a special structure, like an "Eye" Matrix (see Matlab) /// </summary> /// <param name="_n">Number of rows</param> /// <param name="_m">Number of columns</param> /// <param name="structure">Structure Type </param> public Matrix(int _n, int _m, MatrixType type) { noRows = _n; noColumns = _m; values = new double[noRows, noColumns]; switch (type) { case MatrixType.EYE: for (int i = 0; i < noRows; i++) for (int j = 0; j < noColumns; j++) if (i == j) this[i, j] = 1; break; case MatrixType.ONES: for (int i = 0; i < noRows; i++) for (int j = 0; j < noColumns; j++) this[i, j] = 1; break; } }
public int[,] GetMatrix(MatrixType type) { switch (type) { case MatrixType.Type_A: GetMatrixTypeA(); break; case MatrixType.Type_B: GetMatrixTypeB(); break; case MatrixType.Type_C: GetMatrixTypeC(); break; case MatrixType.Type_D: GetMatrixTypeD(); break; default: break; } return this.matrix; }
public static extern IntPtr cvInitMatNDHeader(IntPtr mat, int dims, int[] sizes, MatrixType type, IntPtr data);
public void CrossReferencedDockerfileFromMultipleRepos_ImageGraph(MatrixType matrixType) { TempFolderContext tempFolderContext = TestHelper.UseTempFolder(); GenerateBuildMatrixCommand command = new GenerateBuildMatrixCommand(); command.Options.Manifest = Path.Combine(tempFolderContext.Path, "manifest.json"); command.Options.MatrixType = matrixType; command.Options.ProductVersionComponents = 2; Manifest manifest = CreateManifest( CreateRepo("core/runtime-deps", CreateImage( new Platform[] { CreatePlatform( DockerfileHelper.CreateDockerfile("3.1/runtime-deps/os", tempFolderContext), new string[] { "tag" }) }, productVersion: "3.1")), CreateRepo("core/runtime", CreateImage( new Platform[] { CreatePlatform( DockerfileHelper.CreateDockerfile("3.1/runtime/os", tempFolderContext, "core/runtime-deps:tag"), new string[] { "tag" }) }, productVersion: "3.1")), CreateRepo("runtime-deps", CreateImage( new Platform[] { CreatePlatform( "3.1/runtime-deps/os/Dockerfile", new string[] { "tag" }) }, productVersion: "5.0")), CreateRepo("runtime", CreateImage( new Platform[] { CreatePlatform( DockerfileHelper.CreateDockerfile("5.0/runtime/os", tempFolderContext, "runtime-deps:tag"), new string[] { "tag" }) }, productVersion: "5.0")) ); File.WriteAllText(Path.Combine(tempFolderContext.Path, command.Options.Manifest), JsonConvert.SerializeObject(manifest)); command.LoadManifest(); IEnumerable <BuildMatrixInfo> matrixInfos = command.GenerateMatrixInfo(); Assert.Single(matrixInfos); BuildMatrixInfo matrixInfo = matrixInfos.First(); if (matrixType == MatrixType.PlatformDependencyGraph) { Assert.Single(matrixInfo.Legs); Assert.Equal("3.1-runtime-deps-os-Dockerfile-graph", matrixInfo.Legs[0].Name); string imageBuilderPaths = matrixInfo.Legs[0].Variables.First(variable => variable.Name == "imageBuilderPaths").Value; Assert.Equal($"--path 3.1/runtime-deps/os/Dockerfile --path 3.1/runtime/os/Dockerfile --path 5.0/runtime/os/Dockerfile", imageBuilderPaths); } else { Assert.Equal(2, matrixInfo.Legs.Count); Assert.Equal("3.1-focal", matrixInfo.Legs[0].Name); string imageBuilderPaths = matrixInfo.Legs[0].Variables.First(variable => variable.Name == "imageBuilderPaths").Value; Assert.Equal($"--path 3.1/runtime-deps/os/Dockerfile --path 3.1/runtime/os/Dockerfile", imageBuilderPaths); Assert.Equal("5.0-focal", matrixInfo.Legs[1].Name); imageBuilderPaths = matrixInfo.Legs[1].Variables.First(variable => variable.Name == "imageBuilderPaths").Value; Assert.Equal($"--path 3.1/runtime-deps/os/Dockerfile --path 5.0/runtime/os/Dockerfile", imageBuilderPaths); } }
protected internal override SimpleMatrix <W> createMatrix(int numRows, int numCols, MatrixType type) { return(new SimpleMatrix <W>(numRows, numCols, type)); }
public void MatrixMode(MatrixType matrix) /*GL.MatrixMode(getMatrixMode(matrix));*/ }
/// <summary> /// Construct a identity matrix /// </summary> public Matrix4() { m_type = MatrixType.Normal; Identity(); }
/// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> /// <param name="seed"></param> #else /// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> /// <param name="seed"></param> #endif public CvLSH(int d, int n, int L, int k, MatrixType type, double r, Int64 seed) { _ptr = CvInvoke.cvCreateMemoryLSH(d, n, L, k, type, r, seed); if (_ptr == IntPtr.Zero) { throw new OpenCvSharpException("Failed to create CvLSH"); } }
/// <summary> /// 多次元配列のヘッダを初期化する /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dims">配列の次元数</param> /// <param name="sizes">次元サイズの配列</param> /// <param name="type">配列要素の種類</param> /// <param name="data">行列のヘッダで指定されるデータ</param> /// <returns></returns> #else /// <summary> /// Initializes multi-dimensional array header. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dims">Number of array dimensions. </param> /// <param name="sizes">Array of dimension sizes. </param> /// <param name="type">Type of array elements. The same as for CvMat. </param> /// <param name="data">Optional data pointer assigned to the matrix header. </param> /// <returns></returns> #endif public CvMatND InitMatNDHeader <T>(int dims, int[] sizes, MatrixType type, T[] data) where T : struct { return(Cv.InitMatNDHeader(this, dims, sizes, type, data)); }
/// <summary> /// 多次元配列のヘッダを初期化する /// </summary> /// <param name="dims">配列の次元数</param> /// <param name="sizes">次元サイズの配列</param> /// <param name="type">配列要素の種類</param> /// <returns></returns> #else /// <summary> /// Initializes multi-dimensional array header. /// </summary> /// <param name="dims">Number of array dimensions. </param> /// <param name="sizes">Array of dimension sizes. </param> /// <param name="type">Type of array elements. The same as for CvMat. </param> /// <returns></returns> #endif public CvMatND InitMatNDHeader(int dims, int[] sizes, MatrixType type) { return(Cv.InitMatNDHeader(this, dims, sizes, type)); }
public Matrix(List <double> source, MatrixType type) : this(source.ToArray(), type) { }
public Shape(ShapeVertexDescriptor desc, BoundingVolume bounds, List <Packet> prims, MatrixType matrixType) { Descriptor = desc; Bounds = bounds; Packets = prims; MatrixType = matrixType; }
public Shape(MatrixType matrixType) : this() { MatrixType = matrixType; }
public SimpleMatrix(int numRows, int numCols, MatrixTypesClass type) : this(numRows, numCols, MatrixType.lookup(type) /*MatrixType.lookup(type)*/) { }
/// <summary> /// Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of /// given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. /// </summary> /// <param name="ops">(not supported argument on OpenCvSharp)</param> /// <param name="d"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <returns></returns> #else /// <summary> /// Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of /// given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. /// </summary> /// <param name="ops">(not supported argument on OpenCvSharp)</param> /// <param name="d"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <returns></returns> #endif public static CvLSH CreateLSH(IntPtr ops, int d, int L, int k, MatrixType type) { return Cv.CreateLSH(ops, d, L, k, type, 4, -1); }
/// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> #else /// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> #endif public CvLSH(int d, int n, int L, int k, MatrixType type) : this(d, n, L, k, type, 4, -1) { }
/// <summary> /// Visits the specified type. /// </summary> /// <param name="type">the type.</param> public override void Visit(MatrixType type) { Write("Matrix"); ProcessInitialValueStatus = true; }
/// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> /// <param name="seed"></param> /// <returns></returns> #else /// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> /// <param name="seed"></param> /// <returns></returns> #endif public static CvLSH CreateMemoryLSH(int d, int n, int L, int k, MatrixType type, double r, Int64 seed) { return Cv.CreateMemoryLSH(d, n, L, k, type, r, seed); }
/// <summary> /// Compute an average matrix for all matrices in the calibrators buffer /// </summary> /// <param name="calibrators"></param> /// <param name="mt"></param> /// <returns></returns> public static double[,] matrixAvg(CircularBuffer <SensorCalibratorData> calibrators, MatrixType mt) { double[,] aggregateMatrix = new double[, ] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; double[,] avgMatrix = new double[, ] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; double[,] UsableSize = new double[, ] { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }; for (int i = 0; i < calibrators.Capacity; i++) { for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { if (mt == MatrixType.Roll && !double.IsNaN(calibrators[i].rollCorrection[j, k])) { UsableSize[j, k]++; aggregateMatrix[j, k] += calibrators[i].rollCorrection[j, k]; } else if (mt == MatrixType.Yaw && !double.IsNaN(calibrators[i].yawCorrection[j, k])) { UsableSize[j, k]++; aggregateMatrix[j, k] += calibrators[i].yawCorrection[j, k]; } } } } for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { avgMatrix[j, k] = aggregateMatrix[j, k] / UsableSize[j, k]; } } return(avgMatrix); }
/// <summary> /// ctor,translation matrix. /// </summary> /// <param name="origin">origin of UCS in world coordinate</param> public Matrix4(Vector4 origin) { m_type = MatrixType.TransLation; Identity(); m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z; }
/// <summary> Sets the matrix type that load/push/pop operations should be applied to. </summary> public abstract void SetMatrixMode(MatrixType mode);
void OnChanged(object sender, EventArgs e) { CheckBox clickedButton = sender as CheckBox; //CheckBox clickedButton = (CheckBox)sender; if (clickedButton == null) // just to be on the safe side { return; } //Cancel closes the window if (cancel.Checked) { Close(); } //OK sends the information else if (ok.Checked) { //Sending information to the next form, //that saves and gives away it. MatrixType matrix = MatrixType.RANDOM; NeighbourhoodType neighbourhood = NeighbourhoodType.CONWAY; MeshType mesh = MeshType.SQUARE; if (pointRb.Checked) { matrix = MatrixType.ONE_POINT; } else if (randomRb.Checked) { matrix = MatrixType.RANDOM; } if (ulamRb.Checked) { neighbourhood = NeighbourhoodType.ULAM; } else if (conwayRb.Checked) { neighbourhood = NeighbourhoodType.CONWAY; } else if (knightRb.Checked) { neighbourhood = NeighbourhoodType.KNIGHT; } if (squareRb.Checked) { mesh = MeshType.SQUARE; } else if (triangleRb.Checked) { mesh = MeshType.TRIANGLE; } else if (hexagonRb.Checked) { mesh = MeshType.HEXAGON; } RuleSettings rules = new RuleSettings(matrix, neighbourhood, mesh); rules.ShowDialog(); this.Visible = false; this.Hide(); this.Dispose(); } // Ha az előbbiek felsorolási típusok lesznek, akkor itt konstruáljuk meg // az él-hal szabály párbeszédablakát }
/// <summary> /// Let the setting manager dispatches a delegate /// that generate 2nd27TM matrix. /// </summary> public static void Set2ndTM27ForTransitionMatrix() { MtxType = MatrixType.SecondOrder27; }
public void AddItem(MatrixItem item, MatrixType type) { Data[type].Add(item); }
public static void MatrixMode(MatrixType type) { CurrentMatrixType = type; }
/// <summary> /// Initializes a new instance of the <see cref="HlslGrammar"/> class. /// </summary> public HlslGrammar() { GrammarComments = "Hlsl version 5.0"; Term(string_literal_raw, TokenCategory.String, TokenType.StringLiteral); Punc("::", TokenType.IdentifierSeparator); // ------------------------------------------------------------------------------------ // Comments // ------------------------------------------------------------------------------------ identifier_ns_list.Rule = MakePlusRule(identifier_ns_list, ToTerm("::"), identifier_raw); identifier_dot_list.Rule = MakePlusRule(identifier_dot_list, ToTerm("."), identifier_raw); identifier_ns.Rule = identifier_raw + "::" + identifier_ns_list; identifier_dot.Rule = identifier_or_generic + ToTerm(".") + identifier_dot_list; identifier_or_dot.Rule = identifier | identifier_dot; identifier.Rule |= identifier_ns; semi_opt.Rule = Empty | PreferShiftHere() + ";"; //Prepare term set for conflict resolution _skipTokensInPreview.UnionWith(new[] { ToTerm("."), identifier_raw, ToTerm(","), ToTerm("::"), ToTerm("["), ToTerm("]"), float_literal, integer_literal }); var genericResolverHint = new GenericResolverHint(_skipTokensInPreview); less_than.Rule = genericResolverHint + "<"; // ------------------------------------------------------------------------------------ // Types // ------------------------------------------------------------------------------------ // String string_literal.Rule = string_literal_raw.List(); string_literal_raw.AstNodeCreator = CreateStringRawLiteral; // Add string to literals literal.Rule |= string_literal; float_qualifier.Rule = Keyword("unorm") | Keyword("snorm"); // scalars var scalarTypes = new[] { ScalarType.Bool, ScalarType.Int, ScalarType.UInt, ScalarType.Float, ScalarType.Half, ScalarType.Double }; foreach (var scalarType in scalarTypes) { NonTerminal scalarTerm; var localScalarType = scalarType; if (scalarType == ScalarType.Float) { scalarTerm = new NonTerminal( "float", (context, node) => { var dynamicFloatType = Ast<ScalarType>(node); dynamicFloatType.Name = new Identifier(localScalarType.Name) { Span = SpanConverter.Convert(node.Span) }; dynamicFloatType.Type = localScalarType.Type; dynamicFloatType.Qualifiers = Qualifier.None; if (node.ChildNodes.Count == 2) { dynamicFloatType.Qualifiers = (Qualifier)node.ChildNodes[0].AstNode; } }) { Rule = Keyword("float", true) | float_qualifier + Keyword("float", true) }; } else { scalarTerm = CreateScalarTerminal(scalarType); } if (scalars.Rule == null) scalars.Rule = scalarTerm; else scalars.Rule |= scalarTerm; } // Buffer Rules buffer_type.Rule = TypeName("Buffer") + less_than + simple_type_or_type_name + ">"; // Vectors Rules vector_type.AstNodeCreator = CreateVectorAst; vector_type.Rule = Keyword("vector") + less_than + scalars_or_typename + "," + number + ">"; vector_type_list.Rule = vector_type; // Add all vector int1 int2 int3 int4... float1 float2 float3 float4... etc. foreach (var scalarTypeIt in scalarTypes) { var scalarType = scalarTypeIt; for (var dim = 1; dim <= 4; dim++) { var vectorTypeInstance = new VectorType(scalarTypeIt, dim); var nonGenericType = vectorTypeInstance.ToNonGenericType(); var name = nonGenericType.Name.Text; vector_type_list.Rule |= new NonTerminal(name, (ctx, node) => { var typeName = vectorTypeInstance.ToNonGenericType(SpanConverter.Convert(node.Span)); node.AstNode = typeName; }) { Rule = Keyword(name) }; } } // Matrices matrix_type_simple.Rule = Keyword("matrix"); matrix_type_simple.AstNodeCreator = (ctx, node) => { var typeName = Ast<TypeName>(node); typeName.Name = new Identifier("matrix") { Span = SpanConverter.Convert(node.Span) }; typeName.TypeInference.TargetType = new MatrixType(ScalarType.Float, 4, 4); }; matrix_type.Rule = Keyword("matrix") + less_than + scalars_or_typename + "," + number + "," + number + ">"; matrix_type.AstNodeCreator = CreateMatrixAst; matrix_type_list.Rule = matrix_type | matrix_type_simple; // Add all matrix typedefs: int1x1 int1x2... float1x1 float1x2 float1x3 float1x4... etc. foreach (var scalarTypeIt in scalarTypes) { var scalarType = scalarTypeIt; for (var dimX = 1; dimX <= 4; dimX++) for (var dimY = 1; dimY <= 4; dimY++) { var matrixTypeInstance = new MatrixType(scalarTypeIt, dimY, dimX); var nonGenericType = matrixTypeInstance.ToNonGenericType(); var name = nonGenericType.Name.Text; // var typeName = new TypeName(name) { Alias = matrixTypeInstance }; matrix_type_list.Rule |= new NonTerminal( name, (ctx, node) => { var typeName = matrixTypeInstance.ToNonGenericType(SpanConverter.Convert(node.Span)); node.AstNode = typeName; }) { Rule = Keyword(name) }; } } // Sampler types state_type.Rule = CreateRuleFromObjectTypes( StateType.BlendState, StateType.DepthStencilState, StateType.RasterizerState, SamplerStateType.SamplerState, SamplerStateType.SamplerStateOld, SamplerStateType.SamplerComparisonState); sampler_type.Rule = CreateRuleFromObjectTypes( SamplerType.Sampler, SamplerType.Sampler1D, SamplerType.Sampler2D, SamplerType.Sampler3D, SamplerType.SamplerCube); sampler_type.AstNodeCreator = CreateTypeFromTokenAst<SamplerType>; // Texture types texture_type_profile_4.Rule = CreateRuleFromObjectTypes( TextureType.Texture1D, TextureType.Texture1DArray, TextureType.Texture2D, TextureType.Texture2DArray, TextureType.Texture3D, TextureType.TextureCube); texture_type.Rule = Keyword("texture") | texture_type_profile_4; // ByteAddressBuffer byte_address_buffer.Rule = TypeName("ByteAddressBuffer") | TypeName("RWByteAddressBuffer"); // StructuredBuffer structured_buffer_type.Rule = TypeName("AppendStructuredBuffer") | TypeName("ConsumeStructuredBuffer") | TypeName("RWStructuredBuffer") | TypeName("StructuredBuffer"); structured_buffer.Rule = structured_buffer_type + less_than + scalars_and_vectors + ">"; // RWTexture.* texture_type_profile_5.Rule = TypeName("RWBuffer") | TypeName("RWTexture1D") | TypeName("RWTexture1DArray") | TypeName("RWTexture2D") | TypeName("RWTexture2DArray") | TypeName("RWTexture3D"); texture_generic_simple_type.Rule = texture_type_profile_4 + less_than + scalars_and_vectors + ">" | texture_type_profile_5 + less_than + scalars_and_vectors + ">"; texture_dms_type_profile_5.Rule = TypeName("Texture2DMS") | TypeName("Texture2DMSArray"); texture_generic_dms_type.Rule = texture_dms_type_profile_5 + less_than + scalars_and_vectors + ">" | texture_dms_type_profile_5 + less_than + scalars_and_vectors + "," + number + ">"; texture_generic_type.Rule = texture_generic_simple_type | texture_generic_dms_type; // HullShader/DomainShader InputPatch/OutputPatch patch_type.Rule = TypeName("InputPatch") | TypeName("OutputPatch"); patch_generic_type.Rule = patch_type + less_than + type + "," + number + ">"; texture_type_list.Rule = texture_type | texture_generic_type; // Types used by the geometry shader geometry_stream.Rule = line_stream | point_stream | triangle_stream | stream_output_object; triangle_stream.Rule = TypeName("TriangleStream") + less_than + type + ">"; point_stream.Rule = TypeName("PointStream") + less_than + type + ">"; line_stream.Rule = TypeName("LineStream") + less_than + type + ">"; stream_output_object.Rule = TypeName("StreamOutputObject") + less_than + type + ">"; //// Shader object //// shader_objects.Rule = ToTerm("VertexShader") | "PixelShader" | "GeometryShader"; string_type.Rule = Keyword("string"); // Add string to simple types simple_type.Rule |= string_type; // Add Object types object_type.Rule |= buffer_type | state_type | texture_type_list | byte_address_buffer | structured_buffer | patch_generic_type | interface_specifier | class_specifier | geometry_stream; ////| shader_objects; // Type name typename_for_cast.Rule = identifier + new IdentifierResolverHint(true); identifier_generic_parameter_list.Rule = MakePlusRule(identifier_generic_parameter_list, ToTerm(","), identifier_sub_generic); identifier_sub_generic.Rule = identifier_or_generic; identifier_sub_generic.AstNodeCreator = CreateIdentifierSubGenericAst; //identifier_generic.Rule = identifier + new IdentifierResolverHint(true) + "<" + identifier_generic_parameter_list + ">"; identifier_generic.Rule = identifier + new GenericResolverHint(_skipTokensInPreview) + "<" + identifier_generic_parameter_list + ">"; identifier_or_generic.Rule = identifier + new IdentifierResolverHint(true) | identifier_generic + this.ReduceHere(); type_generic.Rule = identifier_or_generic; // Type used for cast (use valuetype) type_for_cast.Rule = typename_for_cast | value_type; // ------------------------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------------------------ // Add special variable allowed as variable name and keyword identifier_extended.Rule |= Keyword("sample") | Keyword("point"); // postfix_expression postfix_expression.Rule |= compile_expression | asm_expression | state_expression; compile_expression.Rule = Keyword("compile") + identifier + method_invoke_expression_simple; // Match an asm block: asm { ... } asm_expression.Rule = asm_block; KeyTerms.Add(asm_block.Name, asm_block); state_expression.Rule = state_type + state_initializer; // Add cast_expression cast_expression_raw.Rule = "(" + type_for_cast + rank_specifier.ListOpt() + ")" + cast_expression; cast_expression.Rule |= cast_expression_raw; // Syntax is for example: texture = <g_textureref>; identifier_special_reference_expression.Rule = less_than + indexable_identifier + ">"; identifier_keyword.Rule = Keyword("texture"); simple_assignment_expression_statement.Rule |= indexable_identifier + assignment_operator + identifier_special_reference_expression + ";" | identifier_keyword + assignment_operator + identifier_special_reference_expression + ";" | identifier_keyword + assignment_operator + expression + ";"; state_initializer.Rule = "{" + simple_assignment_expression_statement.ListOpt() + "}"; // ------------------------------------------------------------------------------------ // Attribute modifiers // ------------------------------------------------------------------------------------ attribute_qualifier_pre.Rule = attribute_list_opt; attribute_list_opt.Rule = MakeStarRule(attribute_list_opt, null, attribute_modifier); attribute_modifier.Rule = "[" + identifier + "]" | "[" + identifier + "(" + literal_list.Opt() + ")" + "]"; // ------------------------------------------------------------------------------------ // Variable modifiers // ------------------------------------------------------------------------------------ // storageClass = Storage_Class + Type_Modifier storage_qualifier.Rule |= Keyword("extern") | Keyword("nointerpolation") | Keyword("precise") | Keyword("shared") | Keyword("groupshared") | Keyword("static") | Keyword("volatile") | Keyword("row_major") | Keyword("column_major") | Keyword("linear") | Keyword("centroid") | Keyword("noperspective") | Keyword("sample") | Keyword("unsigned") | Keyword("inline"); semantic.Rule = ToTerm(":") + identifier; packoffset.Rule = ToTerm(":") + Keyword("packoffset") + "(" + identifier_or_dot + ")"; register.Rule = ToTerm(":") + Keyword("register") + "(" + indexable_identifier + ")" | ToTerm(":") + Keyword("register") + "(" + identifier + "," + indexable_identifier + ")"; variable_declarator_qualifier_post_hlsl.Rule = Empty | semantic | semantic + packoffset + register.ListOpt() | semantic + register.List() | packoffset + register.ListOpt() | register.List(); variable_declarator_qualifier_post.Rule = variable_declarator_qualifier_post_hlsl; // ------------------------------------------------------------------------------------ // Declarations // ------------------------------------------------------------------------------------ // Add typedef and constant buffer resource declaration.Rule |= typedef_declaration | constant_buffer_resource; indexable_identifier_declarator_list.Rule = MakePlusRule(indexable_identifier_declarator_list, ToTerm(","), indexable_identifier_declarator); // typedef [const] Type Name[Index]; typedef_declaration.Rule = Keyword("typedef") + type + indexable_identifier_declarator_list + ";" | Keyword("typedef") + storage_qualifier + type + indexable_identifier_declarator_list + ";"; annotations.Rule = less_than + variable_declaration_raw.ListOpt() + ">"; annotations_opt.Rule = Empty | annotations; // todo: add annotations_opt to variable_declarator qualifier post // Add annotations to variable declarator variable_declarator_raw.Rule += annotations_opt; // Add special variable_declarator.Rule |= variable_declarator_raw + state_initializer | variable_declarator_raw + state_array_initializer; state_initializer_list.Rule = MakePlusRule(state_initializer_list, ToTerm(","), state_initializer); state_array_initializer.Rule = "{" + state_initializer_list + "}" | "{" + state_initializer_list + "," + "}"; // interface definition interface_specifier.Rule = Keyword("interface") + identifier_or_generic + "{" + method_declaration.ListOpt() + "}"; // class definition class_specifier.Rule = Keyword("class") + identifier_or_generic + class_base_type + "{" + scope_declaration.ListOpt() + "}"; class_base_type_list.Rule = MakePlusRule(class_base_type_list, ToTerm(","), type_generic); class_base_type.Rule = (ToTerm(":") + class_base_type_list).Opt(); // buffer definition constant_buffer_resource_type.Rule = Keyword("cbuffer") | Keyword("tbuffer"); constant_buffer_resource.Rule = attribute_qualifier_pre + constant_buffer_resource_type + identifier.Opt() + register.Opt() + "{" + declaration.ListOpt() + "}" + semi_opt; semantic_list_opt.Rule = semantic.ListOpt(); // Method method_qualifier_post.Rule = semantic_list_opt; method_operator_identifier.Rule = Keyword("operator") + "[" + "]" | Keyword("operator") + "[" + "]" + "[" + "]"; method_special_identifier.Rule = identifier_extended + "." + method_operator_identifier | method_operator_identifier; method_declarator.Rule |= method_special_identifier + "(" + parameter_list + ")"; parameter_qualifier.Rule = storage_qualifier | Keyword("in") | Keyword("out") | Keyword("inout") | Keyword("point") | Keyword("line") | Keyword("lineadj") | Keyword("triangle") | Keyword("triangleadj"); parameter_qualifier.AstNodeCreator = CreateParameterQualifier; parameter_qualifier_pre_list_opt.Rule = parameter_qualifier.ListOpt(); parameter_qualifier_pre.Rule = parameter_qualifier_pre_list_opt; // Make parameter_qualifier_pre transient as there is nothing else to parse then parameter_qualifier_pre_list_opt parameter_qualifier_pre.Flags = TermFlags.IsTransient | TermFlags.NoAstNode; parameter_qualifier_post.Rule = semantic_list_opt | "=" + initializer + semantic_list_opt; parameter_qualifier_post.AstNodeCreator = CreateParameterQualifierPost; // ------------------------------------------------------------------------------------ // Technique/pass // ------------------------------------------------------------------------------------ // technique technique_keyword.Rule = Keyword("technique") | Keyword("Technique") | Keyword("technique10") | Keyword("Technique10") | Keyword("technique11") | Keyword("Technique11"); technique_definition.Rule = attribute_qualifier_pre + technique_keyword + identifier.Opt() + annotations_opt + "{" + pass_definition.List() + "}" + semi_opt; // pass pass_keyword.Rule = Keyword("pass") | Keyword("Pass"); pass_statement.Rule = method_invoke_expression_simple + ";" | simple_assignment_expression_statement; pass_definition.Rule = attribute_qualifier_pre + pass_keyword + identifier.Opt() + annotations_opt + "{" + pass_statement.ListOpt() + "}" + semi_opt; // ------------------------------------------------------------------------------------ // Top Level // ------------------------------------------------------------------------------------ // Add the technique to the top level toplevel_declaration.Rule |= technique_definition; /* //// ------------------------------------------------------------------------------------ //// Paradox Grammar //// ------------------------------------------------------------------------------------ //var identifier_csharp = new NonTerminal("identifier_csharp"); //var group = new NonTerminal("group"); //var using_statement = new NonTerminal("using_statement"); //group.Rule = "group" + identifier + "{" + scope_declaration.ListOpt() + "}"; //identifier_csharp.Rule = MakePlusRule(identifier_csharp, ToTerm("."), identifier); //using_statement.Rule = "using" + identifier + "=" + identifier_csharp + ";" // | "using" + identifier_csharp + ";"; //scope_declaration.Rule |= using_statement; //toplevel_declaration.Rule |= group; */ // ------------------------------------------------------------------------------------ // Globals // ------------------------------------------------------------------------------------ // LanguageFlags = LanguageFlags.NewLineBeforeEOF; LanguageFlags |= LanguageFlags.CreateAst; }
/// <summary> /// Let the setting manager dispatch a delegate /// that generate TM27 Transition Matrix. /// </summary> public static void SetTM27ForTransitionMatrix() { MtxType = MatrixType.Tm27; }
public static extern IntPtr cvCreateLSH(IntPtr ops, int d, int L, int k, MatrixType type, double r, Int64 seed);
public static extern IntPtr cvCreateSparseMat(int dims, [In] int[] sizes, MatrixType type);
public RuleSettings(MatrixType matrix = MatrixType.RANDOM, NeighbourhoodType neighbourhood = NeighbourhoodType.CONWAY, MeshType mesh = MeshType.SQUARE) { //Saves information for MainDrawing this.matrix = matrix; this.neighbourhood = neighbourhood; this.mesh = mesh; Text = "Életjáték él-hal szabályainak beállításai"; sizeX = 700; sizeY = 340; Size = new Size(sizeX, sizeY); cancel = new System.Windows.Forms.CheckBox(); cancel.Appearance = System.Windows.Forms.Appearance.Button; cancel.Text = "Mégsem"; cancel.Parent = this; cancel.Location = new Point(560, 150); cancel.BackColor = Color.Coral; cancel.Show(); cancel.Visible = true; Controls.Add(cancel); ok = new System.Windows.Forms.CheckBox(); ok.Appearance = System.Windows.Forms.Appearance.Button; ok.Text = "OK"; ok.Parent = this; ok.Location = new Point(560, 240); ok.BackColor = Color.Coral; ok.Show(); ok.Visible = true; Controls.Add(ok); //Labelse for panels string birthLabelText = "A születő sejtek szomszédai"; string surviveLabelText = "A túlélő sejtek szomszédai"; Label birth = new Label(); birth.Parent = this; birth.Text = birthLabelText; birth.Location = new Point(30, 30); birth.BackColor = Color.Coral; Label survive = new Label(); survive.Parent = this; survive.Text = surviveLabelText; survive.Location = new Point(270, 30); survive.BackColor = Color.Coral; birth1 = new CheckBox(); birth1.Parent = this; birth1.Location = new Point(30, 90); birth1.Text = "1"; birth1.Checked = false; birth1.BackColor = Color.Coral; birth2 = new CheckBox(); birth2.Parent = this; birth2.Location = new Point(30, 120); birth2.Text = "2"; birth2.Checked = false; birth2.BackColor = Color.Coral; birth3 = new CheckBox(); birth3.Parent = this; birth3.Location = new Point(30, 150); birth3.Text = "3"; birth3.Checked = false; birth3.BackColor = Color.Coral; birth4 = new CheckBox(); birth4.Parent = this; birth4.Location = new Point(30, 180); birth4.Text = "4"; birth4.Checked = false; birth4.BackColor = Color.Coral; birth5 = new CheckBox(); birth5.Parent = this; birth5.Location = new Point(30, 210); birth5.Text = "5"; birth5.Checked = false; birth5.BackColor = Color.Coral; birth6 = new CheckBox(); birth6.Parent = this; birth6.Location = new Point(30, 240); birth6.Text = "6"; birth6.Checked = false; birth6.BackColor = Color.Coral; birth7 = new CheckBox(); birth7.Parent = this; birth7.Location = new Point(150, 90); birth7.Text = "7"; birth7.Checked = false; birth7.BackColor = Color.Coral; birth8 = new CheckBox(); birth8.Parent = this; birth8.Location = new Point(150, 120); birth8.Text = "8"; birth8.Checked = false; birth8.BackColor = Color.Coral; birth9 = new CheckBox(); birth9.Parent = this; birth9.Location = new Point(150, 150); birth9.Text = "9"; birth9.Checked = false; birth9.BackColor = Color.Coral; birth10 = new CheckBox(); birth10.Parent = this; birth10.Location = new Point(150, 180); birth10.Text = "10"; birth10.Checked = false; birth10.BackColor = Color.Coral; birth11 = new CheckBox(); birth11.Parent = this; birth11.Location = new Point(150, 210); birth11.Text = "11"; birth11.Checked = false; birth11.BackColor = Color.Coral; birth12 = new CheckBox(); birth12.Parent = this; birth12.Location = new Point(150, 240); birth12.Text = "12"; birth12.Checked = false; birth12.BackColor = Color.Coral; survive1 = new CheckBox(); survive1.Parent = this; survive1.Location = new Point(270, 90); survive1.Text = "1"; survive1.Checked = false; survive1.BackColor = Color.Coral; survive2 = new CheckBox(); survive2.Parent = this; survive2.Location = new Point(270, 120); survive2.Text = "2"; survive2.Checked = false; survive2.BackColor = Color.Coral; survive3 = new CheckBox(); survive3.Parent = this; survive3.Location = new Point(270, 150); survive3.Text = "3"; survive3.Checked = false; survive3.BackColor = Color.Coral; survive4 = new CheckBox(); survive4.Parent = this; survive4.Location = new Point(270, 180); survive4.Text = "4"; survive4.Checked = false; survive4.BackColor = Color.Coral; survive5 = new CheckBox(); survive5.Parent = this; survive5.Location = new Point(270, 210); survive5.Text = "5"; survive5.Checked = false; survive5.BackColor = Color.Coral; survive6 = new CheckBox(); survive6.Parent = this; survive6.Location = new Point(270, 240); survive6.Text = "6"; survive6.Checked = false; survive6.BackColor = Color.Coral; survive7 = new CheckBox(); survive7.Parent = this; survive7.Location = new Point(390, 90); survive7.Text = "7"; survive7.Checked = false; survive7.BackColor = Color.Coral; survive8 = new CheckBox(); survive8.Parent = this; survive8.Location = new Point(390, 120); survive8.Text = "8"; survive8.Checked = false; survive8.BackColor = Color.Coral; survive9 = new CheckBox(); survive9.Parent = this; survive9.Location = new Point(390, 150); survive9.Text = "9"; survive9.Checked = false; survive9.BackColor = Color.Coral; survive10 = new CheckBox(); survive10.Parent = this; survive10.Location = new Point(390, 180); survive10.Text = "10"; survive10.Checked = false; survive10.BackColor = Color.Coral; survive11 = new CheckBox(); survive11.Parent = this; survive11.Location = new Point(390, 210); survive11.Text = "11"; survive11.Checked = false; survive11.BackColor = Color.Coral; survive12 = new CheckBox(); survive12.Parent = this; survive12.Location = new Point(390, 240); survive12.Text = "12"; survive12.Checked = false; survive12.BackColor = Color.Coral; age = new CheckBox(); age.Parent = this; age.Location = new Point(500, 90); age.Text = "Kor szerinti\nszínezés"; age.Checked = false; age.BackColor = Color.Coral; //Setting the EventHandlers cancel.CheckedChanged += new EventHandler(OnCancelChanged); ok.CheckedChanged += new EventHandler(OnOkChanged); Paint += new PaintEventHandler(OnPaint); CenterToScreen(); }
public TransformPair(MatrixType _type, string _name) { MatType = _type; Name = _name; }
public override IEnumerable <Member> GenerateMembers() { var boolVType = new VectorType(BuiltinType.TypeBool, Components); var mat3Type = new MatrixType(BaseType, 3, 3); var mat4Type = new MatrixType(BaseType, 4, 4); var vec3Type = new VectorType(BaseType, 3); var vec4Type = new VectorType(BaseType, 4); var dquatType = new QuaternionType(BuiltinType.TypeDouble); var dvec3Type = new VectorType(BuiltinType.TypeDouble, 3); var lengthType = new AnyType(BaseType.LengthType); // fields foreach (var f in Fields) { yield return new Field(f, BaseType) { Comment = $"{f}-component" } } ; // predefs yield return(new StaticProperty("Zero", this) { Value = Construct(this, ZeroValue.RepeatTimes(Components)), Comment = "Predefined all-zero quaternion" }); if (!string.IsNullOrEmpty(BaseType.OneValue)) { yield return(new StaticProperty("Ones", this) { Value = Construct(this, OneValue.RepeatTimes(Components)), Comment = "Predefined all-ones quaternion" }); yield return(new StaticProperty("Identity", this) { Value = Construct(this, Fields.Select(f => f == "w" ? OneValue : ZeroValue)), Comment = "Predefined identity quaternion" }); for (var c = 0; c < Components; ++c) { yield return new StaticProperty("Unit" + ArgOfUpper(c), this) { Value = Construct(this, c.ImpulseString(BaseType.OneValue, ZeroValue, Components)), Comment = $"Predefined unit-{ArgOfUpper(c)} quaternion" } } ; } if (BaseType.IsComplex) { yield return(new StaticProperty("ImaginaryOnes", this) { Value = Construct(this, "Complex.ImaginaryOne".RepeatTimes(Components)), Comment = "Predefined all-imaginary-ones quaternion" }); for (var c = 0; c < Components; ++c) { yield return new StaticProperty("ImaginaryUnit" + ArgOfUpper(c), this) { Value = Construct(this, c.ImpulseString("Complex.ImaginaryOne", ZeroValue, Components)), Comment = $"Predefined unit-imaginary-{ArgOfUpper(c)} quaternion" } } ; } // Basetype constants foreach (var constant in BaseType.TypeConstants) { yield return(new StaticProperty(constant, this) { Value = Construct(this, $"{BaseTypeName}.{constant}".RepeatTimes(Components)), Comment = $"Predefined all-{constant} quaternion" }); } // values yield return(new Property("Values", new ArrayType(BaseType)) { GetterLine = $"new[] {{ {CompArgString} }}", Comment = "Returns an array with all values" }); // ctors yield return(new Constructor(this, Fields) { Parameters = Fields.TypedArgs(BaseType), Initializers = Fields, Comment = "Component-wise constructor" }); yield return(new Constructor(this, Fields) { ParameterString = BaseTypeName + " v", Initializers = "v".RepeatTimes(Components), Comment = "all-same-value constructor" }); yield return(new Constructor(this, Fields) { ParameterString = this.NameThat + " q", Initializers = Fields.Select(f => "q." + f), Comment = "copy constructor" }); yield return(new Constructor(this, Fields) { ParameterString = vec3Type.NameThat + " v, " + BaseTypeName + " s", Initializers = new[] { "v.x", "v.y", "v.z", "s" }, Comment = "vector-and-scalar constructor (CAUTION: not angle-axis, use FromAngleAxis instead)" }); if (BaseType.IsFloatingPoint) { // from angle between axes yield return(new Constructor(this, Fields) { Parameters = vec3Type.TypedArgs("u", "v"), Code = new[] { $"var localW = {vec3Type.NameThat}.Cross(u, v);", $"var dot = {vec3Type.NameThat}.Dot(u, v);", $"var q = new {NameThat}(localW.x, localW.y, localW.z, {OneValue} + dot).Normalized;" }, Initializers = new[] { "q.x", "q.y", "q.z", "q.w" }, Comment = "Create a quaternion from two normalized axis (http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors)" }); // from euler angle yield return(new Constructor(this, Fields) { Parameters = vec3Type.TypedArgs("eulerAngle"), Code = new[] { $"var c = {vec3Type.NameThat}.Cos(eulerAngle / 2);", $"var s = {vec3Type.NameThat}.Sin(eulerAngle / 2);", }, Initializers = new[] { "s.x * c.y * c.z - c.x * s.y * s.z", "c.x * s.y * c.z + s.x * c.y * s.z", "c.x * c.y * s.z - s.x * s.y * c.z", "c.x * c.y * c.z + s.x * s.y * s.z" }, Comment = "Create a quaternion from two normalized axis (http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors)" }); // from matrices yield return(new Constructor(this, Fields) { ParameterString = mat3Type.Name + " m", ConstructorChain = "this(FromMat3(m))", Comment = $"Creates a quaternion from the rotational part of a {mat3Type.Name}." }); yield return(new Constructor(this, Fields) { ParameterString = mat4Type.Name + " m", ConstructorChain = "this(FromMat4(m))", Comment = $"Creates a quaternion from the rotational part of a {mat4Type.Name}." }); } // implicit upcasts var implicits = new HashSet <BuiltinType>(); var upcasts = BuiltinType.Upcasts; foreach (var ukvp in upcasts.Where(k => k.Key == BaseType)) { var otherType = ukvp.Value; implicits.Add(otherType); var targetType = new QuaternionType(otherType); yield return(new ImplicitOperator(targetType) { ParameterString = NameThat + " v", CodeString = Construct(targetType, CompString.Select(c => TypeCast(otherType, "v." + c)).ExactlyN(Components, otherType.ZeroValue)), Comment = $"Implicitly converts this to a {targetType.Name}.", }); } // explicit casts foreach (var oType in BuiltinType.BaseTypes) { var otherType = oType; if (otherType.Generic != BaseType.Generic) { continue; // cannot mix generic/non-generic } if (BaseType.IsComplex && !otherType.IsComplex) { continue; // cannot "downcast" complex type } { { var targetType = new VectorType(otherType, Components); yield return(new ExplicitOperator(targetType) { ParameterString = NameThat + " v", CodeString = Construct(targetType, CompString.Select(c => TypeCast(otherType, "v." + c))), Comment = $"Explicitly converts this to a {targetType.Name}." }); } if (otherType == BaseType) { continue; // same type and comps not useful } if (implicits.Contains(otherType)) { continue; // already has an implicit conversion } { var targetType = new QuaternionType(otherType); yield return(new ExplicitOperator(targetType) { ParameterString = NameThat + " v", CodeString = Construct(targetType, CompString.Select(c => TypeCast(otherType, "v." + c))), Comment = $"Explicitly converts this to a {targetType.Name}." }); } } } // from matrices if (BaseType.IsFloatingPoint) { yield return(new ExplicitOperator(this) { ParameterString = mat3Type.Name + " m", CodeString = "FromMat3(m)", Comment = $"Creates a quaternion from the rotational part of a {mat3Type.Name}." }); yield return(new ExplicitOperator(this) { ParameterString = mat4Type.Name + " m", CodeString = "FromMat4(m)", Comment = $"Creates a quaternion from the rotational part of a {mat4Type.Name}." }); } // IEnumerable yield return(new Function(new AnyType($"IEnumerator<{BaseTypeName}>"), "GetEnumerator") { Code = Fields.Select(f => $"yield return {f};"), Comment = "Returns an enumerator that iterates through all components." }); yield return(new Function(new AnyType("IEnumerator"), "IEnumerable.GetEnumerator") { Visibility = "", CodeString = "GetEnumerator()", Comment = "Returns an enumerator that iterates through all components." }); // ToString yield return(new Function(new AnyType("string"), "ToString") { Override = true, CodeString = "ToString(\", \")", Comment = "Returns a string representation of this quaternion using ', ' as a seperator." }); yield return(new Function(new AnyType("string"), "ToString") { ParameterString = "string sep", CodeString = Fields.Aggregated(" + sep + "), Comment = "Returns a string representation of this quaternion using a provided seperator." }); if (!BaseType.Generic) { yield return(new Function(new AnyType("string"), "ToString") { ParameterString = "string sep, IFormatProvider provider", CodeString = Fields.Select(f => f + ".ToString(provider)").Aggregated(" + sep + "), Comment = "Returns a string representation of this quaternion using a provided seperator and a format provider for each component." }); if (BaseType.HasFormatString) { yield return(new Function(new AnyType("string"), "ToString") { ParameterString = "string sep, string format", CodeString = Fields.Select(f => f + ".ToString(format)").Aggregated(" + sep + "), Comment = "Returns a string representation of this quaternion using a provided seperator and a format for each component." }); yield return(new Function(new AnyType("string"), "ToString") { ParameterString = "string sep, string format, IFormatProvider provider", CodeString = Fields.Select(f => f + ".ToString(format, provider)").Aggregated(" + sep + "), Comment = "Returns a string representation of this quaternion using a provided seperator and a format and format provider for each component." }); } } // Parsing if (!BaseType.IsComplex && !BaseType.Generic) { // Parse yield return(new Function(this, "Parse") { Static = true, ParameterString = "string s", CodeString = "Parse(s, \", \")", Comment = "Converts the string representation of the quaternion into a quaternion representation (using ', ' as a separator)." }); yield return(new Function(this, "Parse") { Static = true, ParameterString = "string s, string sep", Code = new[] { "var kvp = s.Split(new[] { sep }, StringSplitOptions.None);", string.Format("if (kvp.Length != {0}) throw new FormatException(\"input has not exactly {0} parts\");", Components), $"return new {NameThat}({Components.ForIndexUpTo(i => $"{BaseTypeName}.Parse(kvp[{i}].Trim())").CommaSeparated()});" }, Comment = "Converts the string representation of the quaternion into a quaternion representation (using a designated separator)." }); if (BaseType.Name != "bool") { yield return(new Function(this, "Parse") { Static = true, ParameterString = "string s, string sep, IFormatProvider provider", Code = new[] { "var kvp = s.Split(new[] { sep }, StringSplitOptions.None);", string.Format("if (kvp.Length != {0}) throw new FormatException(\"input has not exactly {0} parts\");", Components), $"return new {NameThat}({Components.ForIndexUpTo(i => $"{BaseTypeName}.Parse(kvp[{i}].Trim(), provider)").CommaSeparated()});" }, Comment = "Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a type provider)." }); yield return(new Function(this, "Parse") { Static = true, ParameterString = "string s, string sep, NumberStyles style", Code = new[] { "var kvp = s.Split(new[] { sep }, StringSplitOptions.None);", string.Format("if (kvp.Length != {0}) throw new FormatException(\"input has not exactly {0} parts\");", Components), $"return new {NameThat}({Components.ForIndexUpTo(i => $"{BaseTypeName}.Parse(kvp[{i}].Trim(), style)").CommaSeparated()});" }, Comment = "Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a number style)." }); yield return(new Function(this, "Parse") { Static = true, ParameterString = "string s, string sep, NumberStyles style, IFormatProvider provider", Code = new[] { "var kvp = s.Split(new[] { sep }, StringSplitOptions.None);", string.Format("if (kvp.Length != {0}) throw new FormatException(\"input has not exactly {0} parts\");", Components), $"return new {NameThat}({Components.ForIndexUpTo(i => $"{BaseTypeName}.Parse(kvp[{i}].Trim(), style, provider)").CommaSeparated()});" }, Comment = "Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a number style and a format provider)." }); } // TryParse yield return(new Function(BuiltinType.TypeBool, "TryParse") { Static = true, ParameterString = $"string s, out {NameThat} result", CodeString = "TryParse(s, \", \", out result)", Comment = "Tries to convert the string representation of the quaternion into a quaternion representation (using ', ' as a separator), returns false if string was invalid." }); yield return(new Function(BuiltinType.TypeBool, "TryParse") { Static = true, ParameterString = $"string s, string sep, out {NameThat} result", Code = new[] { "result = Zero;", "if (string.IsNullOrEmpty(s)) return false;", "var kvp = s.Split(new[] { sep }, StringSplitOptions.None);", $"if (kvp.Length != {Components}) return false;", $"{BaseTypeName} {CompString.Select(c => c + " = " + ZeroValue).CommaSeparated()};", $"var ok = {Components.ForIndexUpTo(i => $"{BaseTypeName}.TryParse(kvp[{i}].Trim(), out {ArgOf(i)})").Aggregated(" && ")};", $"result = ok ? new {NameThat}({CompArgString}) : Zero;", "return ok;" }, Comment = "Tries to convert the string representation of the quaternion into a quaternion representation (using a designated separator), returns false if string was invalid." }); if (!BaseType.IsBool) { yield return(new Function(BuiltinType.TypeBool, "TryParse") { Static = true, ParameterString = $"string s, string sep, NumberStyles style, IFormatProvider provider, out {NameThat} result", Code = new[] { "result = Zero;", "if (string.IsNullOrEmpty(s)) return false;", "var kvp = s.Split(new[] { sep }, StringSplitOptions.None);", $"if (kvp.Length != {Components}) return false;", $"{BaseTypeName} {CompString.Select(c => c + " = " + ZeroValue).CommaSeparated()};", $"var ok = {Components.ForIndexUpTo(i => $"{BaseTypeName}.TryParse(kvp[{i}].Trim(), style, provider, out {ArgOf(i)})").Aggregated(" && ")};", $"result = ok ? new {NameThat}({CompArgString}) : Zero;", "return ok;" }, Comment = "Tries to convert the string representation of the quaternion into a quaternion representation (using a designated separator and a number style and a format provider), returns false if string was invalid." }); } } // IReadOnlyList yield return(new Property("Count", BuiltinType.TypeInt) { GetterLine = Components.ToString(), Comment = $"Returns the number of components ({Components})." }); yield return(new Indexer(BaseType) { ParameterString = "int index", Getter = SwitchIndex(Components.ForIndexUpTo(i => $"case {i}: return {ArgOf(i)};")), Setter = SwitchIndex(Components.ForIndexUpTo(i => $"case {i}: {ArgOf(i)} = value; break;")), Comment = "Gets/Sets a specific indexed component (a bit slower than direct access)." }); // Equality comparisons yield return(new Function(BuiltinType.TypeBool, "Equals") { ParameterString = NameThat + " rhs", CodeString = Fields.Select(Comparer).Aggregated(" && "), Comment = "Returns true iff this equals rhs component-wise." }); yield return(new Function(BuiltinType.TypeBool, "Equals") { Override = true, ParameterString = "object obj", Code = new[] { "if (ReferenceEquals(null, obj)) return false;", string.Format("return obj is {0} && Equals(({0}) obj);", NameThat) }, Comment = "Returns true iff this equals rhs type- and component-wise." }); yield return(new Operator(BuiltinType.TypeBool, "==") { Parameters = this.LhsRhs(), CodeString = "lhs.Equals(rhs)", Comment = "Returns true iff this equals rhs component-wise." }); yield return(new Operator(BuiltinType.TypeBool, "!=") { Parameters = this.LhsRhs(), CodeString = "!lhs.Equals(rhs)", Comment = "Returns true iff this does not equal rhs (component-wise)." }); yield return(new Function(BuiltinType.TypeInt, "GetHashCode") { Override = true, Code = new[] { "unchecked", "{", $" return {HashCodeFor(Components - 1)};", "}" }, Comment = "Returns a hash code for this instance." }); // Basetype test functions foreach (var kvp in BaseType.TypeTestFuncs) { yield return(new ComponentWiseStaticFunction(Fields, boolVType, kvp.Key, this, "v", kvp.Value)); } // Component-wise static functions yield return(new ComponentWiseStaticFunction(Fields, boolVType, "Equal", this, "lhs", this, "rhs", BaseType.EqualFormat)); yield return(new ComponentWiseStaticFunction(Fields, boolVType, "NotEqual", this, "lhs", this, "rhs", BaseType.NotEqualFormat)); if (BaseType.HasComparisons) { yield return(new ComponentWiseStaticFunction(Fields, boolVType, "GreaterThan", this, "lhs", this, "rhs", "{0} > {1}")); yield return(new ComponentWiseStaticFunction(Fields, boolVType, "GreaterThanEqual", this, "lhs", this, "rhs", "{0} >= {1}")); yield return(new ComponentWiseStaticFunction(Fields, boolVType, "LesserThan", this, "lhs", this, "rhs", "{0} < {1}")); yield return(new ComponentWiseStaticFunction(Fields, boolVType, "LesserThanEqual", this, "lhs", this, "rhs", "{0} <= {1}")); yield return(new ComponentWiseOperator(Fields, boolVType, "<", this, "lhs", this, "rhs", "{0} < {1}")); yield return(new ComponentWiseOperator(Fields, boolVType, "<=", this, "lhs", this, "rhs", "{0} <= {1}")); yield return(new ComponentWiseOperator(Fields, boolVType, ">", this, "lhs", this, "rhs", "{0} > {1}")); yield return(new ComponentWiseOperator(Fields, boolVType, ">=", this, "lhs", this, "rhs", "{0} >= {1}")); } if (BaseType.IsBool) { yield return(new ComponentWiseStaticFunction(Fields, boolVType, "Not", this, "v", "!{0}")); yield return(new ComponentWiseOperator(Fields, this, "!", this, "v", "!{0}")); yield return(new ComponentWiseStaticFunction(Fields, this, "And", this, "lhs", this, "rhs", "{0} && {1}")); yield return(new ComponentWiseStaticFunction(Fields, this, "Nand", this, "lhs", this, "rhs", "!({0} && {1})")); yield return(new ComponentWiseStaticFunction(Fields, this, "Or", this, "lhs", this, "rhs", "{0} || {1}")); yield return(new ComponentWiseStaticFunction(Fields, this, "Nor", this, "lhs", this, "rhs", "!({0} || {1})")); yield return(new ComponentWiseStaticFunction(Fields, this, "Xor", this, "lhs", this, "rhs", "{0} != {1}")); yield return(new ComponentWiseStaticFunction(Fields, this, "Xnor", this, "lhs", this, "rhs", "{0} == {1}")); yield return(new ComponentWiseOperator(Fields, this, "&", this, "lhs", this, "rhs", "{0} && {1}")); yield return(new ComponentWiseOperator(Fields, this, "|", this, "lhs", this, "rhs", "{0} || {1}")); } if (BaseType.HasArithmetics) { // ops yield return(new ComponentWiseOperator(Fields, this, "+", this, "v", "identity") { ReturnOverride = "v" }); if (BaseType.IsSigned) { yield return(new ComponentWiseOperator(Fields, this, "-", this, "v", "-{0}")); } yield return(new ComponentWiseOperator(Fields, this, "+", this, "lhs", this, "rhs", "{0} + {1}")); yield return(new ComponentWiseOperator(Fields, this, "-", this, "lhs", this, "rhs", "{0} - {1}")); yield return(new ComponentWiseOperator(Fields, this, "*", this, "lhs", BaseType, "rhs", "{0} * {1}") { CanScalar0 = false, CanScalar1 = false }); yield return(new ComponentWiseOperator(Fields, this, "*", BaseType, "lhs", this, "rhs", "{0} * {1}") { CanScalar0 = false, CanScalar1 = false }); yield return(new ComponentWiseOperator(Fields, this, "/", this, "lhs", BaseType, "rhs", "{0} / {1}") { CanScalar0 = false, CanScalar1 = false }); // quat-quat-mult yield return(new Operator(this, "*") { Parameters = this.TypedArgs("p", "q"), CodeString = Construct(this, "p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y", "p.w * q.y + p.y * q.w + p.z * q.x - p.x * q.z", "p.w * q.z + p.z * q.w + p.x * q.y - p.y * q.x", "p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z"), Comment = "Returns proper multiplication of two quaternions." }); // quat-vec-mult, vec-quat-mult yield return(new Operator(vec3Type, "*") { Parameters = this.TypedArgs("q").Concat(vec3Type.TypedArgs("v")), Code = new[] { $"var qv = {Construct(vec3Type, "q.x", "q.y", "q.z")};", $"var uv = {vec3Type.Name}.Cross(qv, v);", $"var uuv = {vec3Type.Name}.Cross(qv, uv);", "return v + ((uv * q.w) + uuv) * 2;" }, Comment = "Returns a vector rotated by the quaternion." }); yield return(new Operator(vec4Type, "*") { Parameters = this.TypedArgs("q").Concat(vec4Type.TypedArgs("v")), CodeString = Construct(vec4Type, "q * " + Construct(vec3Type, "v"), "v.w"), Comment = "Returns a vector rotated by the quaternion (preserves v.w)." }); if (BaseType.IsSigned) { yield return(new Operator(vec3Type, "*") { Parameters = vec3Type.TypedArgs("v").Concat(this.TypedArgs("q")), CodeString = "q.Inverse * v", Comment = "Returns a vector rotated by the inverted quaternion." }); yield return(new Operator(vec4Type, "*") { Parameters = vec4Type.TypedArgs("v").Concat(this.TypedArgs("q")), CodeString = "q.Inverse * v", Comment = "Returns a vector rotated by the inverted quaternion (preserves v.w)." }); } // dot yield return(new Function(BaseType, "Dot") { Static = true, Parameters = this.LhsRhs(), CodeString = Fields.Format(DotFormatString).Aggregated(" + "), Comment = "Returns the inner product (dot product, scalar product) of the two quaternions." }); // length yield return(new Property("Length", lengthType) { GetterLine = "(" + lengthType.Name + ")" + SqrtOf(Fields.Select(SqrOf).Aggregated(" + ")), Comment = "Returns the euclidean length of this quaternion." }); yield return(new Property("LengthSqr", BaseType) { GetterLine = Fields.Select(SqrOf).Aggregated(" + "), Comment = "Returns the squared euclidean length of this quaternion." }); // normalized if (!BaseType.IsInteger) { yield return(new Property("Normalized", this) { GetterLine = $"this / {BaseTypeCast}Length", Comment = "Returns a copy of this quaternion with length one (undefined if this has zero length)." }); yield return(new Property("NormalizedSafe", this) { GetterLine = $"this == Zero ? Identity : this / {BaseTypeCast}Length", Comment = "Returns a copy of this quaternion with length one (returns zero if length is zero)." }); } } // Logicals if (BaseType.IsBool) { yield return(new AggregatedProperty(Fields, "MinElement", BaseType, "&&", "Returns the minimal component of this quaternion.")); yield return(new AggregatedProperty(Fields, "MaxElement", BaseType, "||", "Returns the maximal component of this quaternion.")); yield return(new AggregatedProperty(Fields, "All", BaseType, "&&", "Returns true if all component are true.")); yield return(new AggregatedProperty(Fields, "Any", BaseType, "||", "Returns true if any component is true.")); } // floating point if (BaseType.IsFloatingPoint) { // angles yield return(new Property("Angle", BuiltinType.TypeDouble) { GetterLine = "Math.Acos((double)w) * 2.0", Comment = "Returns the represented angle of this quaternion." }); yield return(new Property("Axis", vec3Type) { Getter = new[] { "var s1 = 1 - w * w;", $"if (s1 < 0) return {vec3Type.Name}.UnitZ;", $"var s2 = 1 / {SqrtOf("s1")};", $"return {Construct(vec3Type, BaseTypeCast + "(x * s2)", BaseTypeCast + "(y * s2)", BaseTypeCast + "(z * s2)")};" }, Comment = "Returns the represented axis of this quaternion." }); yield return(new Property("Yaw", BuiltinType.TypeDouble) { GetterLine = "Math.Asin(-2.0 * (double)(x * z - w * y))", Comment = "Returns the represented yaw angle of this quaternion." }); yield return(new Property("Pitch", BuiltinType.TypeDouble) { GetterLine = "Math.Atan2(2.0 * (double)(y * z + w * x), (double)(w * w - x * x - y * y + z * z))", Comment = "Returns the represented pitch angle of this quaternion." }); yield return(new Property("Roll", BuiltinType.TypeDouble) { GetterLine = "Math.Atan2(2.0 * (double)(x * y + w * z), (double)(w * w + x * x - y * y - z * z))", Comment = "Returns the represented roll angle of this quaternion." }); yield return(new Property("EulerAngles", dvec3Type) { GetterLine = Construct(dvec3Type, "Pitch", "Yaw", "Roll"), Comment = "Returns the represented euler angles (pitch, yaw, roll) of this quaternion." }); yield return(new Function(this, "FromAxisAngle") { Static = true, Parameters = BaseType.TypedArgs("angle").Concat(vec3Type.TypedArgs("v")), Code = new[] { "var s = Math.Sin((double)angle * 0.5);", "var c = Math.Cos((double)angle * 0.5);", $"return {Construct(this, BaseTypeCast + "((double)v.x * s)", BaseTypeCast + "((double)v.y * s)", BaseTypeCast + "((double)v.z * s)", BaseTypeCast + "c")};" }, Comment = "Creates a quaternion from an axis and an angle (in radians)." }); yield return(new Function(this, "Rotated") { Parameters = BaseType.TypedArgs("angle").Concat(vec3Type.TypedArgs("v")), CodeString = "this * FromAxisAngle(angle, v)", Comment = "Rotates this quaternion from an axis and an angle (in radians)." }); } // mat casts if (BaseType.IsFloatingPoint) { yield return(new Property("ToMat3", mat3Type) { GetterLine = Construct(mat3Type, "1 - 2 * (y*y + z*z)", "2 * (x*y + w*z)", "2 * (x*z - w*y)", "2 * (x*y - w*z)", "1 - 2 * (x*x + z*z)", "2 * (y*z + w*x)", "2 * (x*z + w*y)", "2 * (y*z - w*x)", "1 - 2 * (x*x + y*y)" ), Comment = $"Creates a {mat3Type.Name} that realizes the rotation of this quaternion" }); yield return(new Property("ToMat4", mat4Type) { GetterLine = Construct(mat4Type, "ToMat3"), Comment = $"Creates a {mat4Type.Name} that realizes the rotation of this quaternion" }); yield return(new Function(this, "FromMat3") { Static = true, Parameters = mat3Type.TypedArgs("m"), Code = new[] { "var fourXSquaredMinus1 = m.m00 - m.m11 - m.m22;", "var fourYSquaredMinus1 = m.m11 - m.m00 - m.m22;", "var fourZSquaredMinus1 = m.m22 - m.m00 - m.m11;", "var fourWSquaredMinus1 = m.m00 + m.m11 + m.m22;", "var biggestIndex = 0;", "var fourBiggestSquaredMinus1 = fourWSquaredMinus1;", "if(fourXSquaredMinus1 > fourBiggestSquaredMinus1)", "{", " fourBiggestSquaredMinus1 = fourXSquaredMinus1;", " biggestIndex = 1;", "}", "if(fourYSquaredMinus1 > fourBiggestSquaredMinus1)", "{", " fourBiggestSquaredMinus1 = fourYSquaredMinus1;", " biggestIndex = 2;", "}", "if(fourZSquaredMinus1 > fourBiggestSquaredMinus1)", "{", " fourBiggestSquaredMinus1 = fourZSquaredMinus1;", " biggestIndex = 3;", "}", "var biggestVal = Math.Sqrt((double)fourBiggestSquaredMinus1 + 1.0) * 0.5;", "var mult = 0.25 / biggestVal;", "switch(biggestIndex)", "{", $" case 0: return {Construct(this, BaseTypeCast + "((double)(m.m12 - m.m21) * mult)", BaseTypeCast + "((double)(m.m20 - m.m02) * mult)", BaseTypeCast + "((double)(m.m01 - m.m10) * mult)", BaseTypeCast + "(biggestVal)")};", $" case 1: return {Construct(this, BaseTypeCast + "(biggestVal)", BaseTypeCast + "((double)(m.m01 + m.m10) * mult)", BaseTypeCast + "((double)(m.m20 + m.m02) * mult)", BaseTypeCast + "((double)(m.m12 - m.m21) * mult)")};", $" case 2: return {Construct(this, BaseTypeCast + "((double)(m.m01 + m.m10) * mult)", BaseTypeCast + "(biggestVal)", BaseTypeCast + "((double)(m.m12 + m.m21) * mult)", BaseTypeCast + "((double)(m.m20 - m.m02) * mult)")};", $" default: return {Construct(this, BaseTypeCast + "((double)(m.m20 + m.m02) * mult)", BaseTypeCast + "((double)(m.m12 + m.m21) * mult)", BaseTypeCast + "(biggestVal)", BaseTypeCast + "((double)(m.m01 - m.m10) * mult)")};", "}" }, Comment = $"Creates a quaternion from the rotational part of a {mat4Type.Name}." }); yield return(new Function(this, "FromMat4") { Static = true, Parameters = mat4Type.TypedArgs("m"), CodeString = $"FromMat3({Construct(mat3Type, "m")})", Comment = $"Creates a quaternion from the rotational part of a {mat3Type.Name}." }); } if (BaseType.IsSigned) { yield return(new Property("Conjugate", this) { GetterLine = Construct(this, "-x", "-y", "-z", "w"), Comment = "Returns the conjugated quaternion" }); yield return(new Property("Inverse", this) { GetterLine = "Conjugate / LengthSqr", Comment = "Returns the inverse quaternion" }); } if (BaseType.HasArithmetics) { // cross yield return(new Function(this, "Cross") { Static = true, Parameters = this.TypedArgs("q1", "q2"), CodeString = Construct(this, "q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y", "q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z", "q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x", "q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z"), Comment = "Returns the cross product between two quaternions." }); // mix if (BaseType.IsFloatingPoint) { yield return(new Function(this, "Mix") { Static = true, Parameters = this.TypedArgs("x", "y").Concat(BaseType.TypedArgs("a")), Code = new[] { "var cosTheta = (double)Dot(x, y);", "if (cosTheta > 1 - float.Epsilon)", " return Lerp(x, y, a);", "else", "{", " var angle = Math.Acos((double)cosTheta);", string.Format(" return {0}( (Math.Sin((1 - (double)a) * angle) * {1}x + Math.Sin((double)a * angle) * {1}y) / Math.Sin(angle) );", BaseType.Name == "double" ? "" : "(" + this.Name + ")", BaseType.Name == "double" ? "" : "(" + dquatType.Name + ")"), "}", }, Comment = "Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions)." }); yield return(new Function(this, "SLerp") { Static = true, Parameters = this.TypedArgs("x", "y").Concat(BaseType.TypedArgs("a")), Code = new[] { "var z = y;", "var cosTheta = (double)Dot(x, y);", "if (cosTheta < 0) { z = -y; cosTheta = -cosTheta; }", "if (cosTheta > 1 - float.Epsilon)", " return Lerp(x, z, a);", "else", "{", " var angle = Math.Acos((double)cosTheta);", string.Format(" return {0}( (Math.Sin((1 - (double)a) * angle) * {1}x + Math.Sin((double)a * angle) * {1}z) / Math.Sin(angle) );", BaseType.Name == "double" ? "" : "(" + this.Name + ")", BaseType.Name == "double" ? "" : "(" + dquatType.Name + ")"), "}", }, Comment = "Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions)." }); yield return(new Function(this, "Squad") { Static = true, Parameters = this.TypedArgs("q1", "q2", "s1", "s2").Concat(BaseType.TypedArgs("h")), CodeString = "Mix(Mix(q1, q2, h), Mix(s1, s2, h), 2 * (1 - h) * h)", Comment = "Applies squad interpolation of these quaternions" }); } // linear interpolation yield return(new ComponentWiseStaticFunction(Fields, this, "Lerp", this, "min", this, "max", this, "a", "{0} * (1-{2}) + {1} * {2}")); } } } }
public static extern IntPtr cvCreateMemoryLSH(int d, int n, int L, int k, MatrixType type, double r, Int64 seed);
private SHP1(EndianBinaryReader reader, int offset, BMDInfo modelstats = null) { Shapes = new List <Shape>(); RemapTable = new List <int>(); reader.BaseStream.Seek(offset, System.IO.SeekOrigin.Begin); reader.SkipInt32(); int shp1Size = reader.ReadInt32(); int entryCount = reader.ReadInt16(); reader.SkipInt16(); if (modelstats != null) { modelstats.SHP1Size = shp1Size; } int shapeHeaderDataOffset = reader.ReadInt32(); int shapeRemapTableOffset = reader.ReadInt32(); int unusedOffset = reader.ReadInt32(); int attributeDataOffset = reader.ReadInt32(); int matrixIndexDataOffset = reader.ReadInt32(); int primitiveDataOffset = reader.ReadInt32(); int matrixDataOffset = reader.ReadInt32(); int PacketInfoDataOffset = reader.ReadInt32(); reader.BaseStream.Seek(offset + shapeRemapTableOffset, System.IO.SeekOrigin.Begin); // Remap table for (int i = 0; i < entryCount; i++) { RemapTable.Add(reader.ReadInt16()); } int highestIndex = J3DUtility.GetHighestValue(RemapTable); // Packet data List <Tuple <int, int> > packetData = new List <Tuple <int, int> >(); // <packet size, packet offset> int packetDataCount = (shp1Size - PacketInfoDataOffset) / 8; reader.BaseStream.Seek(PacketInfoDataOffset + offset, System.IO.SeekOrigin.Begin); for (int i = 0; i < packetDataCount; i++) { packetData.Add(new Tuple <int, int>(reader.ReadInt32(), reader.ReadInt32())); } // Matrix data List <Tuple <int, int> > matrixData = new List <Tuple <int, int> >(); // <index count, start index> List <int[]> matrixIndices = new List <int[]>(); int matrixDataCount = (PacketInfoDataOffset - matrixDataOffset) / 8; reader.BaseStream.Seek(matrixDataOffset + offset, System.IO.SeekOrigin.Begin); for (int i = 0; i < matrixDataCount; i++) { reader.SkipInt16(); matrixData.Add(new Tuple <int, int>(reader.ReadInt16(), reader.ReadInt32())); } for (int i = 0; i < matrixDataCount; i++) { reader.BaseStream.Seek(offset + matrixIndexDataOffset + (matrixData[i].Item2 * 2), System.IO.SeekOrigin.Begin); int[] indices = new int[matrixData[i].Item1]; for (int j = 0; j < matrixData[i].Item1; j++) { indices[j] = reader.ReadInt16(); } matrixIndices.Add(indices); } // Shape data List <Shape> tempShapeList = new List <Shape>(); reader.BaseStream.Seek(offset + shapeHeaderDataOffset, System.IO.SeekOrigin.Begin); for (int i = 0; i < highestIndex + 1; i++) { MatrixType matrixType = (MatrixType)reader.ReadByte(); reader.SkipByte(); int packetCount = reader.ReadInt16(); int shapeAttributeOffset = reader.ReadInt16(); int shapeMatrixDataIndex = reader.ReadInt16(); int firstPacketIndex = reader.ReadInt16(); reader.SkipInt16(); BoundingVolume shapeVol = new BoundingVolume(reader); long curOffset = reader.BaseStream.Position; ShapeVertexDescriptor descriptor = new ShapeVertexDescriptor(reader, offset + attributeDataOffset + shapeAttributeOffset); List <Packet> shapePackets = new List <Packet>(); for (int j = 0; j < packetCount; j++) { int packetSize = packetData[j + firstPacketIndex].Item1; int packetOffset = packetData[j + firstPacketIndex].Item2; Packet pack = new Packet(packetSize, packetOffset + primitiveDataOffset + offset, matrixIndices[j + firstPacketIndex]); pack.ReadPrimitives(reader, descriptor); shapePackets.Add(pack); } tempShapeList.Add(new Shape(descriptor, shapeVol, shapePackets, matrixType)); reader.BaseStream.Seek(curOffset, System.IO.SeekOrigin.Begin); } for (int i = 0; i < entryCount; i++) { Shapes.Add(tempShapeList[RemapTable[i]]); } reader.BaseStream.Seek(offset + shp1Size, System.IO.SeekOrigin.Begin); }
public static extern IntPtr cvInitMatHeader(IntPtr mat, int rows, int cols, MatrixType type, IntPtr data, int step);
/// <summary> /// default ctor /// </summary> public Matrix4() { m_type = MatrixType.Normal; Identity(); }
/// <summary> /// Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of /// given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. /// </summary> /// <param name="ops">(not supported argument on OpenCvSharp)</param> /// <param name="d"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> #else /// <summary> /// Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of /// given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. /// </summary> /// <param name="ops">(not supported argument on OpenCvSharp)</param> /// <param name="d"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> #endif public CvLSH(IntPtr ops, int d, int L, int k, MatrixType type, double r) : this(ops, d, L, k, type, r, -1) { }
/// <summary> /// ctor,translation matrix. /// </summary> /// <param name="origin">origin of ucs in world coordinate</param> public Matrix4(Vector4 origin) { m_type = MatrixType.Translation; Identity(); m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z; }
/// <summary> /// Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of /// given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. /// </summary> /// <param name="ops">(not supported argument on OpenCvSharp)</param> /// <param name="d"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> /// <param name="seed"></param> /// <returns></returns> #else /// <summary> /// Construct a Locality Sensitive Hash (LSH) table, for indexing d-dimensional vectors of /// given type. Vectors will be hashed L times with k-dimensional p-stable (p=2) functions. /// </summary> /// <param name="ops">(not supported argument on OpenCvSharp)</param> /// <param name="d"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> /// <param name="seed"></param> /// <returns></returns> #endif public static CvLSH CreateLSH(IntPtr ops, int d, int L, int k, MatrixType type, double r, Int64 seed) { return Cv.CreateLSH(ops, d, L, k, type, r, seed); }
/// <summary> /// scale matrix constructor /// </summary> /// <param name="scale">scale factor</param> public Matrix4(float scale) { m_type = MatrixType.Scale; Identity(); m_matrix[0, 0] = m_matrix[1, 1] = m_matrix[2, 2] = scale; }
/// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> #else /// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <param name="r"></param> #endif public CvLSH(int d, int n, int L, int k, MatrixType type, double r) : this(d, n, L, k, type, r, -1) { }
protected virtual void Visit(MatrixType type) { Write("Matrix"); ProcessInitialValueStatus = true; }
/// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <returns></returns> #else /// <summary> /// Construct in-memory LSH table, with n bins. /// </summary> /// <param name="d"></param> /// <param name="n"></param> /// <param name="L"></param> /// <param name="k"></param> /// <param name="type"></param> /// <returns></returns> #endif public static CvLSH CreateMemoryLSH(int d, int n, int L, int k, MatrixType type) { return Cv.CreateMemoryLSH(d, n, L, k, type, 4, -1); }
/// <summary> /// 总的像素bit位点阵,一定是8的倍数 /// </summary> /// <param name="content">每页的字模数据</param> /// <param name="colorType"></param> /// <param name="matrixType"></param> /// <returns></returns> public List <byte> ToBytes(Bitmap content, ColorType colorType, MatrixType matrixType) { List <byte> result = new List <byte>(); int height = content.Height; int width = content.Width; if (colorType == ColorType.SINGLE) // 单色 { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x += 8) { byte bits = 0x00; for (int i = 0; i < 8; i++) { Color rgb = content.GetPixel(x + i, y); int r = rgb.R; int g = rgb.G; bool flag = r >= 127 | g >= 127; bits += (byte)((flag ? 0 : 1) << (7 - i)); } result.Add(bits); } } } else if (colorType == ColorType.DOUBLE) // 双色 { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x += 8) { byte Rbits = 0x00; byte Gbits = 0x00; for (int i = 0; i < 8; i++) { Color rgb = content.GetPixel(x + i, y); int r = rgb.R; int g = rgb.G; Rbits += (byte)((r >= 127 ? 0 : 1) << (7 - i)); Gbits += (byte)((g >= 127 ? 0 : 1) << (7 - i)); } if (matrixType == MatrixType.RG)//r+g { result.Add(Rbits); result.Add(Gbits); } else//g+r,r+g的屏幕反过来就是g+r { result.Add(Gbits); result.Add(Rbits); } } } } else if (colorType == ColorType.THREE) // 双色 { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x += 8) { byte Rbits = 0x00; byte Gbits = 0x00; byte Bbits = 0x00; for (int i = 0; i < 8; i++) { Color rgb = content.GetPixel(x + i, y); int r = rgb.R; int g = rgb.G; int b = rgb.B; Rbits += (byte)((r >= 127 ? 0 : 1) << (7 - i)); Gbits += (byte)((g >= 127 ? 0 : 1) << (7 - i)); Bbits += (byte)((b >= 127 ? 0 : 1) << (7 - i)); } result.Add(Rbits); result.Add(Gbits); result.Add(Bbits); } } } else //全彩 { for (int y = 0; y < height; y++) //遍历每列 { for (int x = 0; x < width; x++) //遍历每行 { Color rgb = content.GetPixel(x, y); int r = rgb.R; //红色像素值 int g = rgb.G; //绿色像素值 int b = rgb.B; //蓝色像素值 //按照协议,RGB565模式对像素值编码,红色取高5位,绿色取高6位,蓝色取高5位,低位舍弃,从而一个像素需要用两个字节表示 //int data1 = ((r >> 3) << 11) & 0xF800;//红色 //int data2 = ((g >> 2) << 5) & 0x07E0;//绿色 //int data3 = (b >> 3) & 0x001F;//蓝色 //byte[] dbytes = System.BitConverter.GetBytes(data1 + data2 + data3); int val = rgb.R >> 8 << 11; val |= rgb.G >> 2 << 5; val |= rgb.B >> 8; // 获取RGB单色,并填充低位 int cRed = (val & 0xf800) >> 8; int cGreen = (val & 0x07E0) >> 3; int cBlue = (val & 0x001F) << 3; int n888Color = (cRed << 16) + (cGreen << 8) + (cBlue << 0); byte[] dbytes = System.BitConverter.GetBytes(n888Color); result.Add(dbytes[0]); result.Add(dbytes[1]); } } } return(result); }
public void MatrixMode(MatrixType matrix) => GL.MatrixMode(getMatrixMode(matrix));
public override Node Visit(BinaryExpression expression) { // First, dispatch to resolve type of node at deeper level base.Visit(expression); var leftType = expression.Left.TypeInference.TargetType; var rightType = expression.Right.TypeInference.TargetType; var returnType = expression.TypeInference.ExpectedType ?? expression.TypeInference.TargetType; bool isNumericOperator = true; switch (expression.Operator) { case BinaryOperator.LogicalAnd: case BinaryOperator.LogicalOr: isNumericOperator = false; returnType = GetBinaryImplicitConversionType(expression.Span, leftType, rightType, true); expression.TypeInference.TargetType = returnType; break; case BinaryOperator.Less: case BinaryOperator.LessEqual: case BinaryOperator.Greater: case BinaryOperator.GreaterEqual: case BinaryOperator.Equality: case BinaryOperator.Inequality: isNumericOperator = false; returnType = GetBinaryImplicitConversionType(expression.Span, leftType, rightType, false); TypeBase resultType = ScalarType.Bool; if (returnType is VectorType) { resultType = new VectorType(ScalarType.Bool, ((VectorType)returnType).Dimension); } else if (returnType is MatrixType) { var matrixType = (MatrixType)returnType; resultType = new MatrixType(ScalarType.Bool, matrixType.RowCount, matrixType.ColumnCount); } expression.TypeInference.TargetType = resultType; break; } if (returnType != null) { if (returnType == ScalarType.Bool && isNumericOperator) { var typeToCheck = leftType ?? rightType; if (typeToCheck != null) { return(ConvertExpressionToBool(expression, typeToCheck)); } } } if (!isNumericOperator || CastHelper.NeedConvertForBinary(leftType, returnType)) { expression.Left = Cast(leftType, returnType, expression.Left); } if (!isNumericOperator || CastHelper.NeedConvertForBinary(rightType, returnType)) { expression.Right = Cast(rightType, returnType, expression.Right); } return(expression); }
/// <summary> /// Initializes a new instance of the <see cref="HlslGrammar"/> class. /// </summary> public HlslGrammar() { GrammarComments = "Hlsl version 5.0"; Term(string_literal_raw, TokenCategory.String, TokenType.StringLiteral); Punc("::", TokenType.IdentifierSeparator); // ------------------------------------------------------------------------------------ // Comments // ------------------------------------------------------------------------------------ identifier_ns_list.Rule = MakePlusRule(identifier_ns_list, ToTerm("::"), identifier_raw); identifier_dot_list.Rule = MakePlusRule(identifier_dot_list, ToTerm("."), identifier_raw); identifier_ns.Rule = identifier_raw + "::" + identifier_ns_list; identifier_dot.Rule = identifier_or_generic + ToTerm(".") + identifier_dot_list; identifier_or_dot.Rule = identifier | identifier_dot; identifier.Rule |= identifier_ns; semi_opt.Rule = Empty | PreferShiftHere() + ";"; //Prepare term set for conflict resolution _skipTokensInPreview.UnionWith(new[] { ToTerm("."), identifier_raw, ToTerm(","), ToTerm("::"), ToTerm("["), ToTerm("]"), float_literal, integer_literal }); var genericResolverHint = new GenericResolverHint(_skipTokensInPreview); less_than.Rule = genericResolverHint + "<"; // ------------------------------------------------------------------------------------ // Types // ------------------------------------------------------------------------------------ // String string_literal.Rule = string_literal_raw.List(); string_literal_raw.AstNodeCreator = CreateStringRawLiteral; // Add string to literals literal.Rule |= string_literal; float_qualifier.Rule = Keyword("unorm") | Keyword("snorm"); // scalars var scalarTypes = new[] { ScalarType.Bool, ScalarType.Int, ScalarType.UInt, ScalarType.Float, ScalarType.Half, ScalarType.Double }; foreach (var scalarType in scalarTypes) { NonTerminal scalarTerm; var localScalarType = scalarType; if (scalarType == ScalarType.Float) { scalarTerm = new NonTerminal( "float", (context, node) => { var dynamicFloatType = Ast <ScalarType>(node); dynamicFloatType.Name = new Identifier(localScalarType.Name) { Span = SpanConverter.Convert(node.Span) }; dynamicFloatType.Type = localScalarType.Type; dynamicFloatType.Qualifiers = Qualifier.None; if (node.ChildNodes.Count == 2) { dynamicFloatType.Qualifiers = (Qualifier)node.ChildNodes[0].AstNode; } }) { Rule = Keyword("float", true) | float_qualifier + Keyword("float", true) }; } else { scalarTerm = CreateScalarTerminal(scalarType); } if (scalars.Rule == null) { scalars.Rule = scalarTerm; } else { scalars.Rule |= scalarTerm; } } // Buffer Rules buffer_type.Rule = TypeName("Buffer") + less_than + simple_type_or_type_name + ">"; // Vectors Rules vector_type.AstNodeCreator = CreateVectorAst; vector_type.Rule = Keyword("vector") + less_than + scalars_or_typename + "," + number + ">"; vector_type_list.Rule = vector_type; // Add all vector int1 int2 int3 int4... float1 float2 float3 float4... etc. foreach (var scalarTypeIt in scalarTypes) { var scalarType = scalarTypeIt; for (var dim = 1; dim <= 4; dim++) { var vectorTypeInstance = new VectorType(scalarTypeIt, dim); var nonGenericType = vectorTypeInstance.ToNonGenericType(); var name = nonGenericType.Name.Text; vector_type_list.Rule |= new NonTerminal(name, (ctx, node) => { var typeName = vectorTypeInstance.ToNonGenericType(SpanConverter.Convert(node.Span)); node.AstNode = typeName; }) { Rule = Keyword(name) }; } } // Matrices matrix_type_simple.Rule = Keyword("matrix"); matrix_type_simple.AstNodeCreator = (ctx, node) => { var typeName = Ast <TypeName>(node); typeName.Name = new Identifier("matrix") { Span = SpanConverter.Convert(node.Span) }; typeName.TypeInference.TargetType = new MatrixType(ScalarType.Float, 4, 4); }; matrix_type.Rule = Keyword("matrix") + less_than + scalars_or_typename + "," + number + "," + number + ">"; matrix_type.AstNodeCreator = CreateMatrixAst; matrix_type_list.Rule = matrix_type | matrix_type_simple; // Add all matrix typedefs: int1x1 int1x2... float1x1 float1x2 float1x3 float1x4... etc. foreach (var scalarTypeIt in scalarTypes) { var scalarType = scalarTypeIt; for (var dimX = 1; dimX <= 4; dimX++) { for (var dimY = 1; dimY <= 4; dimY++) { var matrixTypeInstance = new MatrixType(scalarTypeIt, dimX, dimY); var nonGenericType = matrixTypeInstance.ToNonGenericType(); var name = nonGenericType.Name.Text; // var typeName = new TypeName(name) { Alias = matrixTypeInstance }; matrix_type_list.Rule |= new NonTerminal( name, (ctx, node) => { var typeName = matrixTypeInstance.ToNonGenericType(SpanConverter.Convert(node.Span)); node.AstNode = typeName; }) { Rule = Keyword(name) }; } } } // Sampler types state_type.Rule = CreateRuleFromObjectTypes( StateType.BlendState, StateType.DepthStencilState, StateType.RasterizerState, StateType.SamplerState, StateType.SamplerStateOld, StateType.SamplerComparisonState); sampler_type.Rule = CreateRuleFromObjectTypes( SamplerType.Sampler, SamplerType.Sampler1D, SamplerType.Sampler2D, SamplerType.Sampler3D, SamplerType.SamplerCube); sampler_type.AstNodeCreator = CreateTypeFromTokenAst <ObjectType>; // Texture types texture_type_profile_4.Rule = CreateRuleFromObjectTypes( TextureType.Texture1D, TextureType.Texture1DArray, TextureType.Texture2D, TextureType.Texture2DArray, TextureType.Texture3D, TextureType.TextureCube); texture_type.Rule = Keyword("texture") | texture_type_profile_4; // ByteAddressBuffer byte_address_buffer.Rule = TypeName("ByteAddressBuffer") | TypeName("RWByteAddressBuffer"); // StructuredBuffer structured_buffer_type.Rule = TypeName("AppendStructuredBuffer") | TypeName("ConsumeStructuredBuffer") | TypeName("RWStructuredBuffer") | TypeName("StructuredBuffer"); structured_buffer.Rule = structured_buffer_type + less_than + scalars_and_vectors + ">"; // RWTexture.* texture_type_profile_5.Rule = TypeName("RWBuffer") | TypeName("RWTexture1D") | TypeName("RWTexture1DArray") | TypeName("RWTexture2D") | TypeName("RWTexture2DArray") | TypeName("RWTexture3D"); texture_generic_simple_type.Rule = texture_type_profile_4 + less_than + scalars_and_vectors + ">" | texture_type_profile_5 + less_than + scalars_and_vectors + ">"; texture_dms_type_profile_5.Rule = TypeName("Texture2DMS") | TypeName("Texture2DMSArray"); texture_generic_dms_type.Rule = texture_dms_type_profile_5 + less_than + scalars_and_vectors + ">" | texture_dms_type_profile_5 + less_than + scalars_and_vectors + "," + number + ">"; texture_generic_type.Rule = texture_generic_simple_type | texture_generic_dms_type; // HullShader/DomainShader InputPatch/OutputPatch patch_type.Rule = TypeName("InputPatch") | TypeName("OutputPatch"); patch_generic_type.Rule = patch_type + less_than + type + "," + number + ">"; texture_type_list.Rule = texture_type | texture_generic_type; // Types used by the geometry shader geometry_stream.Rule = line_stream | point_stream | triangle_stream | stream_output_object; triangle_stream.Rule = TypeName("TriangleStream") + less_than + type + ">"; point_stream.Rule = TypeName("PointStream") + less_than + type + ">"; line_stream.Rule = TypeName("LineStream") + less_than + type + ">"; stream_output_object.Rule = TypeName("StreamOutputObject") + less_than + type + ">"; //// Shader object //// shader_objects.Rule = ToTerm("VertexShader") | "PixelShader" | "GeometryShader"; string_type.Rule = Keyword("string"); // Add string to simple types simple_type.Rule |= string_type; // Add Object types object_type.Rule |= buffer_type | state_type | texture_type_list | byte_address_buffer | structured_buffer | patch_generic_type | interface_specifier | class_specifier | geometry_stream; ////| shader_objects; // Type name typename_for_cast.Rule = identifier + new IdentifierResolverHint(true); identifier_generic_parameter_list.Rule = MakePlusRule(identifier_generic_parameter_list, ToTerm(","), identifier_sub_generic); identifier_sub_generic.Rule = identifier_or_generic; identifier_sub_generic.AstNodeCreator = CreateIdentifierSubGenericAst; //identifier_generic.Rule = identifier + new IdentifierResolverHint(true) + "<" + identifier_generic_parameter_list + ">"; identifier_generic.Rule = identifier + new GenericResolverHint(_skipTokensInPreview) + "<" + identifier_generic_parameter_list + ">"; identifier_or_generic.Rule = identifier + new IdentifierResolverHint(true) | identifier_generic + this.ReduceHere(); type_generic.Rule = identifier_or_generic; // Type used for cast (use valuetype) type_for_cast.Rule = typename_for_cast | value_type; // ------------------------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------------------------ // Add special variable allowed as variable name and keyword identifier_extended.Rule |= Keyword("sample") | Keyword("point"); // postfix_expression postfix_expression.Rule |= compile_expression | asm_expression | state_expression; compile_expression.Rule = Keyword("compile") + identifier + method_invoke_expression_simple; // Match an asm block: asm { ... } asm_expression.Rule = asm_block; KeyTerms.Add(asm_block.Name, asm_block); state_expression.Rule = state_type + state_initializer; // Add cast_expression cast_expression_raw.Rule = "(" + type_for_cast + rank_specifier.ListOpt() + ")" + cast_expression; cast_expression.Rule |= cast_expression_raw; // Syntax is for example: texture = <g_textureref>; identifier_special_reference_expression.Rule = less_than + indexable_identifier + ">"; identifier_keyword.Rule = Keyword("texture"); simple_assignment_expression_statement.Rule |= indexable_identifier + assignment_operator + identifier_special_reference_expression + ";" | identifier_keyword + assignment_operator + identifier_special_reference_expression + ";" | identifier_keyword + assignment_operator + expression + ";"; state_initializer.Rule = "{" + simple_assignment_expression_statement.ListOpt() + "}"; // ------------------------------------------------------------------------------------ // Attribute modifiers // ------------------------------------------------------------------------------------ attribute_qualifier_pre.Rule = attribute_list_opt; attribute_list_opt.Rule = MakeStarRule(attribute_list_opt, null, attribute_modifier); attribute_modifier.Rule = "[" + identifier + "]" | "[" + identifier + "(" + literal_list.Opt() + ")" + "]"; // ------------------------------------------------------------------------------------ // Variable modifiers // ------------------------------------------------------------------------------------ // storageClass = Storage_Class + Type_Modifier storage_qualifier.Rule |= Keyword("extern") | Keyword("nointerpolation") | Keyword("precise") | Keyword("shared") | Keyword("groupshared") | Keyword("static") | Keyword("volatile") | Keyword("row_major") | Keyword("column_major") | Keyword("linear") | Keyword("centroid") | Keyword("noperspective") | Keyword("sample") | Keyword("unsigned") | Keyword("inline"); semantic.Rule = ToTerm(":") + identifier; packoffset.Rule = ToTerm(":") + Keyword("packoffset") + "(" + identifier_or_dot + ")"; register.Rule = ToTerm(":") + Keyword("register") + "(" + indexable_identifier + ")" | ToTerm(":") + Keyword("register") + "(" + identifier + "," + indexable_identifier + ")"; variable_declarator_qualifier_post_hlsl.Rule = Empty | semantic | semantic + packoffset + register.ListOpt() | semantic + register.List() | packoffset + register.ListOpt() | register.List(); variable_declarator_qualifier_post.Rule = variable_declarator_qualifier_post_hlsl; // ------------------------------------------------------------------------------------ // Declarations // ------------------------------------------------------------------------------------ // Add typedef and constant buffer resource declaration.Rule |= typedef_declaration | constant_buffer_resource; indexable_identifier_declarator_list.Rule = MakePlusRule(indexable_identifier_declarator_list, ToTerm(","), indexable_identifier_declarator); // typedef [const] Type Name[Index]; typedef_declaration.Rule = Keyword("typedef") + type + indexable_identifier_declarator_list + ";" | Keyword("typedef") + storage_qualifier + type + indexable_identifier_declarator_list + ";"; annotations.Rule = less_than + variable_declaration_raw.ListOpt() + ">"; annotations_opt.Rule = Empty | annotations; // todo: add annotations_opt to variable_declarator qualifier post // Add annotations to variable declarator variable_declarator_raw.Rule += annotations_opt; // Add special variable_declarator.Rule |= variable_declarator_raw + state_initializer | variable_declarator_raw + state_array_initializer; state_initializer_list.Rule = MakePlusRule(state_initializer_list, ToTerm(","), state_initializer); state_array_initializer.Rule = "{" + state_initializer_list + "}" | "{" + state_initializer_list + "," + "}"; // interface definition interface_specifier.Rule = Keyword("interface") + identifier_or_generic + "{" + method_declaration.ListOpt() + "}"; // class definition class_specifier.Rule = Keyword("class") + identifier_or_generic + class_base_type + "{" + scope_declaration.ListOpt() + "}"; class_base_type_list.Rule = MakePlusRule(class_base_type_list, ToTerm(","), type_generic); class_base_type.Rule = (ToTerm(":") + class_base_type_list).Opt(); // buffer definition constant_buffer_resource_type.Rule = Keyword("cbuffer") | Keyword("tbuffer") | Keyword("rgroup"); constant_buffer_resource_type.AstNodeCreator = CreateConstantBufferTypeAst; constant_buffer_resource.Rule = attribute_qualifier_pre + constant_buffer_resource_type + identifier.Opt() + register.Opt() + "{" + declaration.ListOpt() + "}" + semi_opt; semantic_list_opt.Rule = semantic.ListOpt(); // Method method_qualifier_post.Rule = semantic_list_opt; method_operator_identifier.Rule = Keyword("operator") + "[" + "]" | Keyword("operator") + "[" + "]" + "[" + "]"; method_special_identifier.Rule = identifier_extended + "." + method_operator_identifier | method_operator_identifier; method_declarator.Rule |= method_special_identifier + "(" + parameter_list + ")"; parameter_qualifier.Rule = storage_qualifier | Keyword("in") | Keyword("out") | Keyword("inout") | Keyword("point") | Keyword("line") | Keyword("lineadj") | Keyword("triangle") | Keyword("triangleadj"); parameter_qualifier.AstNodeCreator = CreateParameterQualifier; parameter_qualifier_pre_list_opt.Rule = parameter_qualifier.ListOpt(); parameter_qualifier_pre.Rule = parameter_qualifier_pre_list_opt; // Make parameter_qualifier_pre transient as there is nothing else to parse then parameter_qualifier_pre_list_opt parameter_qualifier_pre.Flags = TermFlags.IsTransient | TermFlags.NoAstNode; parameter_qualifier_post.Rule = semantic_list_opt | "=" + initializer + semantic_list_opt; parameter_qualifier_post.AstNodeCreator = CreateParameterQualifierPost; // ------------------------------------------------------------------------------------ // Technique/pass // ------------------------------------------------------------------------------------ // technique technique_keyword.Rule = Keyword("technique") | Keyword("Technique") | Keyword("technique10") | Keyword("Technique10") | Keyword("technique11") | Keyword("Technique11"); technique_definition.Rule = attribute_qualifier_pre + technique_keyword + identifier.Opt() + annotations_opt + "{" + pass_definition.List() + "}" + semi_opt; // pass pass_keyword.Rule = Keyword("pass") | Keyword("Pass"); pass_statement.Rule = method_invoke_expression_simple + ";" | simple_assignment_expression_statement; pass_definition.Rule = attribute_qualifier_pre + pass_keyword + identifier.Opt() + annotations_opt + "{" + pass_statement.ListOpt() + "}" + semi_opt; // ------------------------------------------------------------------------------------ // Top Level // ------------------------------------------------------------------------------------ // Add the technique to the top level toplevel_declaration.Rule |= technique_definition; /* * //// ------------------------------------------------------------------------------------ * //// Stride Grammar * //// ------------------------------------------------------------------------------------ * //var identifier_csharp = new NonTerminal("identifier_csharp"); * //var group = new NonTerminal("group"); * //var using_statement = new NonTerminal("using_statement"); * //group.Rule = "group" + identifier + "{" + scope_declaration.ListOpt() + "}"; * //identifier_csharp.Rule = MakePlusRule(identifier_csharp, ToTerm("."), identifier); * //using_statement.Rule = "using" + identifier + "=" + identifier_csharp + ";" * // | "using" + identifier_csharp + ";"; * //scope_declaration.Rule |= using_statement; * //toplevel_declaration.Rule |= group; */ // ------------------------------------------------------------------------------------ // Globals // ------------------------------------------------------------------------------------ // LanguageFlags = LanguageFlags.NewLineBeforeEOF; LanguageFlags |= LanguageFlags.CreateAst; }
/// <summary> /// rotation and translation matrix constructor /// </summary> /// <param name="xAxis">x Axis</param> /// <param name="yAxis">y Axis</param> /// <param name="zAxis">z Axis</param> /// <param name="origin">origin</param> public Matrix4(Vector4 xAxis, Vector4 yAxis, Vector4 zAxis, Vector4 origin) { m_type = MatrixType.RotationAndTransLation; Identity(); m_matrix[0, 0] = xAxis.X; m_matrix[0, 1] = xAxis.Y; m_matrix[0, 2] = xAxis.Z; m_matrix[1, 0] = yAxis.X; m_matrix[1, 1] = yAxis.Y; m_matrix[1, 2] = yAxis.Z; m_matrix[2, 0] = zAxis.X; m_matrix[2, 1] = zAxis.Y; m_matrix[2, 2] = zAxis.Z; m_matrix[3, 0] = origin.X; m_matrix[3, 1] = origin.Y; m_matrix[3, 2] = origin.Z; }
public bool AnimateTransform(MatrixType whichMatrix, Matrix transform) { AnimatableMatrix aniMatrix = GetMatrix(whichMatrix); return GetMatrix(whichMatrix).AnimateTo(transform * aniMatrix.Matrix); }