private int GetRowHitsCount(int value, int row) { int maxHits = 0; int hits = 0; int col = 0; while (col <= Board.IndexMaxCols) { if (IsHit(row, col, value)) { hits++; } else { maxHits = Math.Max(maxHits, hits); hits = 0; } col++; // move to the next column } return(Math.Max(maxHits, hits)); }
void SmoothTransition(MyLodStrategyInfo strategyInfo, float timeDeltaSeconds, float distance, ref int currentLod, ref int targetLod, ref float transition) { if (transition == 0) // the transition has not started { //Check the suitable lod targetLod = GetTheBestLodWithHisteresis(strategyInfo, distance, currentLod); //Lod is fine, therefore no transition if (currentLod == targetLod) { targetLod = -1; return; } //Lod is not found, init transition: m_transitionStartedAtDistance = distance; //And swap target and current lod int swappedLod = targetLod; targetLod = currentLod; currentLod = swappedLod; } // The transition should start float deltaTransitionTime = timeDeltaSeconds / MAX_TRANSITION_TIME_IN_SECS; float deltaTransitionDistance = Math.Abs(m_transitionStartedAtDistance - distance) / m_lodTransitionDistances[Math.Min(currentLod, targetLod)]; float deltaTransition = Math.Max(deltaTransitionDistance, deltaTransitionTime); deltaTransition = Math.Min(deltaTransition, MAX_TRANSITION_PER_FRAME); transition = transition + deltaTransition; if (transition >= 1.0f) { transition = 0.0f; targetLod = -1; } }
public static int Max(int a, int b) { return(MathCore.Max(a, b)); }
/// <summary> /// {@inheritDoc} /// </summary> protected internal override double DoSolve() { double min = this.Min; double max = this.Max; this.VerifyInterval(min, max); double relativeAccuracy = this.RelativeAccuracy; double absoluteAccuracy = this.AbsoluteAccuracy; double functionValueAccuracy = this.FunctionValueAccuracy; // x2 is the last root approximation // x is the new approximation and new x2 for next round // x0 < x1 < x2 does not hold here double x0 = min; double y0 = this.ComputeObjectiveValue(x0); if (FastMath.Abs(y0) < functionValueAccuracy) { return(x0); } double x1 = max; double y1 = this.ComputeObjectiveValue(x1); if (FastMath.Abs(y1) < functionValueAccuracy) { return(x1); } if (y0 * y1 > 0) { throw new NoBracketingException(x0, x1, y0, y1); } double x2 = 0.5 * (x0 + x1); double y2 = this.ComputeObjectiveValue(x2); double oldx = double.PositiveInfinity; while (true) { // quadratic interpolation through x0, x1, x2 double q = (x2 - x1) / (x1 - x0); double a = q * (y2 - (1 + q) * y1 + q * y0); double b = (2 * q + 1) * y2 - (1 + q) * (1 + q) * y1 + q * q * y0; double c = (1 + q) * y2; double delta = b * b - 4 * a * c; double x; double denominator; if (delta >= 0.0) { // choose a denominator larger in magnitude double dplus = b + FastMath.Sqrt(delta); double dminus = b - FastMath.Sqrt(delta); denominator = FastMath.Abs(dplus) > FastMath.Abs(dminus) ? dplus : dminus; } else { // take the modulus of (B +/- FastMath.sqrt(delta)) denominator = FastMath.Sqrt(b * b - delta); } if (denominator != 0) { x = x2 - 2.0 * c * (x2 - x1) / denominator; // perturb x if it exactly coincides with x1 or x2 // the equality tests here are intentional while (x == x1 || x == x2) { x += absoluteAccuracy; } } else { // extremely rare case, get a random number to skip it x = min + MyUtils.Random() * (max - min); oldx = double.PositiveInfinity; } double y = this.ComputeObjectiveValue(x); // check for convergence double tolerance = FastMath.Max(relativeAccuracy * FastMath.Abs(x), absoluteAccuracy); if (FastMath.Abs(x - oldx) <= tolerance || FastMath.Abs(y) <= functionValueAccuracy) { return(x); } // prepare the next iteration x0 = x1; y0 = y1; x1 = x2; y1 = y2; x2 = x; y2 = y; oldx = x; } }
public static TextPosition ToLocation(this Source src) { var from = new TextPosition(new LineNumber(Math.Max(src.Line, 1)), new CharacterNumber(Math.Max(src.Column + 1, 1))); // TODO: (needs TextRegion in uno, or maybe i can just remove this? maybe change to optional end in SourceReference //var to = new TextPosition(new LineNumber(Math.Max(src.EndLine, 1)), new CharacterNumber(Math.Max(src.EndColumn + 1, 1))); //if (to > from) // return new TextRegion(from, to); return(from); }
private static int DistanceBetween(int square1, int square2) { ChessBoard.RankAndFileOf(square1, out int r1, out int f1); ChessBoard.RankAndFileOf(square2, out int r2, out int f2); return(SMath.Max(SMath.Abs(r1 - r2), SMath.Abs(f1 - f2))); }
/** We need to combine operations and report invalid operations (like * overlapping replaces that are not completed nested). Inserts to * same index need to be combined etc... Here are the cases: * * I.i.u I.j.v leave alone, nonoverlapping * I.i.u I.i.v combine: Iivu * * R.i-j.u R.x-y.v | i-j in x-y delete first R * R.i-j.u R.i-j.v delete first R * R.i-j.u R.x-y.v | x-y in i-j ERROR * R.i-j.u R.x-y.v | boundaries overlap ERROR * * Delete special case of replace (text==null): * D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) * * I.i.u R.x-y.v | i in (x+1)-y delete I (since insert before * we're not deleting i) * I.i.u R.x-y.v | i not in (x+1)-y leave alone, nonoverlapping * R.x-y.v I.i.u | i in x-y ERROR * R.x-y.v I.x.u R.x-y.uv (combine, delete I) * R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping * * I.i.u = insert u before op @ index i * R.x-y.u = replace x-y indexed tokens with u * * First we need to examine replaces. For any replace op: * * 1. wipe out any insertions before op within that range. * 2. Drop any replace op before that is contained completely within * that range. * 3. Throw exception upon boundary overlap with any previous replace. * * Then we can deal with inserts: * * 1. for any inserts to same index, combine even if not adjacent. * 2. for any prior replace with same left boundary, combine this * insert with replace and delete this replace. * 3. throw exception if index in same range as previous replace * * Don't actually delete; make op null in list. Easier to walk list. * Later we can throw as we add to index -> op map. * * Note that I.2 R.2-2 will wipe out I.2 even though, technically, the * inserted stuff would be before the replace range. But, if you * add tokens in front of a method body '{' and then delete the method * body, I think the stuff before the '{' you added should disappear too. * * Return a map from token index to operation. */ protected virtual IDictionary <int, RewriteOperation> ReduceToSingleOperationPerIndex(IList <RewriteOperation> rewrites) { //System.out.println("rewrites="+rewrites); // WALK REPLACES for (int i = 0; i < rewrites.Count; i++) { RewriteOperation op = rewrites[i]; if (op == null) { continue; } if (!(op is ReplaceOp)) { continue; } ReplaceOp rop = (ReplaceOp)rewrites[i]; // Wipe prior inserts within range var inserts = GetKindOfOps(rewrites, typeof(InsertBeforeOp), i); for (int j = 0; j < inserts.Count; j++) { InsertBeforeOp iop = (InsertBeforeOp)inserts[j]; if (iop.index == rop.index) { // E.g., insert before 2, delete 2..2; update replace // text to include insert before, kill insert rewrites[iop.instructionIndex] = null; rop.text = iop.text.ToString() + (rop.text != null ? rop.text.ToString() : string.Empty); } else if (iop.index > rop.index && iop.index <= rop.lastIndex) { // delete insert as it's a no-op. rewrites[iop.instructionIndex] = null; } } // Drop any prior replaces contained within var prevReplaces = GetKindOfOps(rewrites, typeof(ReplaceOp), i); for (int j = 0; j < prevReplaces.Count; j++) { ReplaceOp prevRop = (ReplaceOp)prevReplaces[j]; if (prevRop.index >= rop.index && prevRop.lastIndex <= rop.lastIndex) { // delete replace as it's a no-op. rewrites[prevRop.instructionIndex] = null; continue; } // throw exception unless disjoint or identical bool disjoint = prevRop.lastIndex <rop.index || prevRop.index> rop.lastIndex; bool same = prevRop.index == rop.index && prevRop.lastIndex == rop.lastIndex; // Delete special case of replace (text==null): // D.i-j.u D.x-y.v | boundaries overlap combine to max(min)..max(right) if (prevRop.text == null && rop.text == null && !disjoint) { //System.out.println("overlapping deletes: "+prevRop+", "+rop); rewrites[prevRop.instructionIndex] = null; // kill first delete rop.index = Math.Min(prevRop.index, rop.index); rop.lastIndex = Math.Max(prevRop.lastIndex, rop.lastIndex); #if !PORTABLE Console.WriteLine("new rop " + rop); #endif } else if (!disjoint && !same) { throw new ArgumentException("replace op boundaries of " + rop + " overlap with previous " + prevRop); } } } // WALK INSERTS for (int i = 0; i < rewrites.Count; i++) { RewriteOperation op = (RewriteOperation)rewrites[i]; if (op == null) { continue; } if (!(op is InsertBeforeOp)) { continue; } InsertBeforeOp iop = (InsertBeforeOp)rewrites[i]; // combine current insert with prior if any at same index var prevInserts = GetKindOfOps(rewrites, typeof(InsertBeforeOp), i); for (int j = 0; j < prevInserts.Count; j++) { InsertBeforeOp prevIop = (InsertBeforeOp)prevInserts[j]; if (prevIop.index == iop.index) { // combine objects // convert to strings...we're in process of toString'ing // whole token buffer so no lazy eval issue with any templates iop.text = CatOpText(iop.text, prevIop.text); // delete redundant prior insert rewrites[prevIop.instructionIndex] = null; } } // look for replaces where iop.index is in range; error var prevReplaces = GetKindOfOps(rewrites, typeof(ReplaceOp), i); for (int j = 0; j < prevReplaces.Count; j++) { ReplaceOp rop = (ReplaceOp)prevReplaces[j]; if (iop.index == rop.index) { rop.text = CatOpText(iop.text, rop.text); rewrites[i] = null; // delete current insert continue; } if (iop.index >= rop.index && iop.index <= rop.lastIndex) { throw new ArgumentException("insert op " + iop + " within boundaries of previous " + rop); } } } // System.out.println("rewrites after="+rewrites); IDictionary <int, RewriteOperation> m = new Dictionary <int, RewriteOperation>(); for (int i = 0; i < rewrites.Count; i++) { RewriteOperation op = (RewriteOperation)rewrites[i]; if (op == null) { continue; // ignore deleted ops } RewriteOperation existing; if (m.TryGetValue(op.index, out existing) && existing != null) { throw new Exception("should only be one op per index"); } m[op.index] = op; } //System.out.println("index to op: "+m); return(m); }
/* * ControlPolygonFlatEnough : * Check if the control polygon of a Bezier curve is flat enough * for recursive subdivision to bottom out. * Point *V; Control points * int degree; Degree of polynomiaL * */ static bool ControlPolygonFlatEnough(Point[] V, int degree) { int i; /* Index variable */ double[] distance; /* Distances from pts to line */ double max_distance_above; /* maximum of these */ double max_distance_below; double error; /* Precision of root */ double intercept_1, intercept_2, left_intercept, right_intercept; double a, b, c; /* Coefficients of implicit */ /* eqn for line from V[0]-V[deg]*/ /* Find the perpendicular distance */ /* from each interior control point to */ /* line connecting V[0] and V[degree] */ distance = new double[degree + 1]; // (double*)malloc((unsigned)(degree + 1) * sizeof(double)); { double abSquared; /* Derive the implicit equation for line connecting first *' * /* and last control points */ a = V[0].Y - V[degree].Y; b = V[degree].X - V[0].X; c = V[0].X * V[degree].Y - V[degree].X * V[0].Y; abSquared = (a * a) + (b * b); for (i = 1; i < degree; i++) { /* Compute distance from each of the points to that line */ distance[i] = a * V[i].X + b * V[i].Y + c; if (distance[i] > 0.0) { distance[i] = (distance[i] * distance[i]) / abSquared; } if (distance[i] < 0.0) { distance[i] = -((distance[i] * distance[i]) / abSquared); } } } /* Find the largest distance */ max_distance_above = 0.0; max_distance_below = 0.0; for (i = 1; i < degree; i++) { if (distance[i] < 0.0) { max_distance_below = Math.Min(max_distance_below, distance[i]); } ; if (distance[i] > 0.0) { max_distance_above = Math.Max(max_distance_above, distance[i]); } } // free((char*)distance); { double det, dInv; double a1, b1, c1, a2, b2, c2; /* Implicit equation for zero line */ a1 = 0.0; b1 = 1.0; c1 = 0.0; /* Implicit equation for "above" line */ a2 = a; b2 = b; c2 = c + max_distance_above; det = a1 * b2 - a2 * b1; dInv = 1.0 / det; intercept_1 = (b1 * c2 - b2 * c1) * dInv; /* Implicit equation for "below" line */ a2 = a; b2 = b; c2 = c + max_distance_below; det = a1 * b2 - a2 * b1; dInv = 1.0 / det; intercept_2 = (b1 * c2 - b2 * c1) * dInv; } /* Compute intercepts of bounding box */ left_intercept = Math.Min(intercept_1, intercept_2); right_intercept = Math.Max(intercept_1, intercept_2); error = 0.5 * (right_intercept - left_intercept); return(error < EPSILON); }
public static SvdResult ComputeSvd(double[,] matrix) { double[,] U, V; double[] s; // Derived from LINPACK code. // Initialize. double[,] A = matrix.Copy(); int m = matrix.RowCount(); int n = matrix.ColumnCount(); int nu = M.Min(m, n); s = new double[M.Min(m + 1, n)]; U = new double[m, nu]; V = new double[n, n]; var e = new double[n]; var work = new double[m]; bool wantu = true; bool wantv = true; // Reduce A to bidiagonal form, storing the diagonal elements // in s and the super-diagonal elements in e. int nct = M.Min(m - 1, n); int nrt = M.Max(0, M.Min(n - 2, m)); for (int k = 0; k < M.Max(nct, nrt); k++) { if (k < nct) { // Compute the transformation for the k-th column and // place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { s[k] = Functions.Hypotenuse(s[k], A[i, k]); } if (s[k] != 0.0) { if (A[k, k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i, k] /= s[k]; } A[k, k] += 1.0; } s[k] = -s[k]; } for (int j = k + 1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { // Apply the transformation. double t = 0; for (int i = k; i < m; i++) { t += A[i, k] * A[i, j]; } t = (-t) / A[k, k]; for (int i = k; i < m; i++) { A[i, j] += t * A[i, k]; } } // Place the k-th row of A into e for the // subsequent calculation of the row transformation. e[j] = A[k, j]; } if (wantu & (k < nct)) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) { U[i, k] = A[i, k]; } } if (k < nrt) { // Compute the k-th row transformation and place the // k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k + 1; i < n; i++) { e[k] = Functions.Hypotenuse(e[k], e[i]); } if (e[k] != 0.0) { if (e[k + 1] < 0.0) { e[k] = -e[k]; } for (int i = k + 1; i < n; i++) { e[i] /= e[k]; } e[k + 1] += 1.0; } e[k] = -e[k]; if ((k + 1 < m) & (e[k] != 0.0)) { // Apply the transformation. for (int i = k + 1; i < m; i++) { work[i] = 0.0; } for (int j = k + 1; j < n; j++) { for (int i = k + 1; i < m; i++) { work[i] += e[j] * A[i, j]; } } for (int j = k + 1; j < n; j++) { double t = (-e[j]) / e[k + 1]; for (int i = k + 1; i < m; i++) { A[i, j] += t * work[i]; } } } if (wantv) { // Place the transformation in V for subsequent // back multiplication. for (int i = k + 1; i < n; i++) { V[i, k] = e[i]; } } } } // Set up the final bidiagonal matrix or order p. int p = M.Min(n, m + 1); if (nct < n) { s[nct] = A[nct, nct]; } if (m < p) { s[p - 1] = 0.0; } if (nrt + 1 < p) { e[nrt] = A[nrt, p - 1]; } e[p - 1] = 0.0; // If required, generate U. if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { U[i, j] = 0.0; } U[j, j] = 1.0; } for (int k = nct - 1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i, k] * U[i, j]; } t = (-t) / U[k, k]; for (int i = k; i < m; i++) { U[i, j] += t * U[i, k]; } } for (int i = k; i < m; i++) { U[i, k] = -U[i, k]; } U[k, k] = 1.0 + U[k, k]; for (int i = 0; i < k - 1; i++) { U[i, k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i, k] = 0.0; } U[k, k] = 1.0; } } } // If required, generate V. if (wantv) { for (int k = n - 1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k + 1; i < n; i++) { t += V[i, k] * V[i, j]; } t = (-t) / V[k + 1, k]; for (int i = k + 1; i < n; i++) { V[i, j] += t * V[i, k]; } } } for (int i = 0; i < n; i++) { V[i, k] = 0.0; } V[k, k] = 1.0; } } // Main iteration loop for the singular values. int pp = p - 1; int iter = 0; double eps = M.Pow(2.0, -52.0); while (p > 0) { int k, kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and // s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for (k = p - 2; k >= -1; k--) { if (k == -1) { break; } if (M.Abs(e[k]) <= eps * (M.Abs(s[k]) + M.Abs(s[k + 1]))) { e[k] = 0.0; break; } } if (k == p - 2) { kase = 4; } else { int ks; for (ks = p - 1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? M.Abs(e[ks]) : 0.0) + (ks != k + 1 ? M.Abs(e[ks - 1]) : 0.0); if (M.Abs(s[ks]) <= eps * t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p - 1) { kase = 1; } else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { double f = e[p - 2]; e[p - 2] = 0.0; for (int j = p - 2; j >= k; j--) { double t = Functions.Hypotenuse(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; if (j != k) { f = (-sn) * e[j - 1]; e[j - 1] = cs * e[j - 1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i, j] + sn * V[i, p - 1]; V[i, p - 1] = (-sn) * V[i, j] + cs * V[i, p - 1]; V[i, j] = t; } } } } break; // Split at negligible s(k). case 2: { double f = e[k - 1]; e[k - 1] = 0.0; for (int j = k; j < p; j++) { double t = Functions.Hypotenuse(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; f = (-sn) * e[j]; e[j] = cs * e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs * U[i, j] + sn * U[i, k - 1]; U[i, k - 1] = (-sn) * U[i, j] + cs * U[i, k - 1]; U[i, j] = t; } } } } break; // Perform one qr step. case 3: { // Calculate the shift. double scale = M.Max(M.Max(M.Max(M.Max(M.Abs(s[p - 1]), M.Abs(s[p - 2])), M.Abs(e[p - 2])), M.Abs(s[k])), M.Abs(e[k])); double sp = s[p - 1] / scale; double spm1 = s[p - 2] / scale; double epm1 = e[p - 2] / scale; double sk = s[k] / scale; double ek = e[k] / scale; double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; double c = (sp * epm1) * (sp * epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = M.Sqrt(b * b + c); if (b < 0.0) { shift = -shift; } shift = c / (b + shift); } double f = (sk + sp) * (sk - sp) + shift; double g = sk * ek; // Chase zeros. for (int j = k; j < p - 1; j++) { double t = Functions.Hypotenuse(f, g); double cs = f / t; double sn = g / t; if (j != k) { e[j - 1] = t; } f = cs * s[j] + sn * e[j]; e[j] = cs * e[j] - sn * s[j]; g = sn * s[j + 1]; s[j + 1] = cs * s[j + 1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i, j] + sn * V[i, j + 1]; V[i, j + 1] = (-sn) * V[i, j] + cs * V[i, j + 1]; V[i, j] = t; } } t = Functions.Hypotenuse(f, g); cs = f / t; sn = g / t; s[j] = t; f = cs * e[j] + sn * s[j + 1]; s[j + 1] = (-sn) * e[j] + cs * s[j + 1]; g = sn * e[j + 1]; e[j + 1] = cs * e[j + 1]; if (wantu && (j < m - 1)) { for (int i = 0; i < m; i++) { t = cs * U[i, j] + sn * U[i, j + 1]; U[i, j + 1] = (-sn) * U[i, j] + cs * U[i, j + 1]; U[i, j] = t; } } } e[p - 2] = f; iter = iter + 1; } break; // Convergence. case 4: { // Make the singular values positive. if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i <= pp; i++) { V[i, k] = -V[i, k]; } } } // Order the singular values. while (k < pp) { if (s[k] >= s[k + 1]) { break; } double t = s[k]; s[k] = s[k + 1]; s[k + 1] = t; if (wantv && (k < n - 1)) { for (int i = 0; i < n; i++) { t = V[i, k + 1]; V[i, k + 1] = V[i, k]; V[i, k] = t; } } if (wantu && (k < m - 1)) { for (int i = 0; i < m; i++) { t = U[i, k + 1]; U[i, k + 1] = U[i, k]; U[i, k] = t; } } k++; } iter = 0; p--; } break; } } //Complete -- Return SVD Result return(new SvdResult(U, s, V)); }
/// <summary> /// {@inheritDoc} </summary> protected internal override sealed double DoSolve() { // Get initial solution double x0 = this.Min; double x1 = this.Max; double f0 = this.ComputeObjectiveValue(x0); double f1 = this.ComputeObjectiveValue(x1); // If one of the bounds is the exact root, return it. Since these are // not under-approximations or over-approximations, we can return them // regardless of the allowed solutions. if (f0 == 0.0) { return(x0); } if (f1 == 0.0) { return(x1); } // Verify bracketing of initial solution. this.VerifyBracketing(x0, x1); // Get accuracies. double ftol = this.FunctionValueAccuracy; double atol = this.AbsoluteAccuracy; double rtol = this.RelativeAccuracy; // Keep finding better approximations. while (true) { // Calculate the next approximation. double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); double fx = this.ComputeObjectiveValue(x); // If the new approximation is the exact root, return it. Since // this is not an under-approximation or an over-approximation, // we can return it regardless of the allowed solutions. if (fx == 0.0) { return(x); } // Update the bounds with the new approximation. x0 = x1; f0 = f1; x1 = x; f1 = fx; // If the function value of the last approximation is too small, // given the function value accuracy, then we can't get closer to // the root than we already are. if (FastMath.Abs(f1) <= ftol) { return(x1); } // If the current interval is within the given accuracies, we // are satisfied with the current approximation. if (FastMath.Abs(x1 - x0) < FastMath.Max(rtol * FastMath.Abs(x1), atol)) { return(x1); } } }
/// <summary> /// CSA形式の局面図をsfen形式にする /// </summary> /// <param name="pos"></param> /// <param name="kif"></param> /// <returns></returns> public static string CsaToSfen(string[] csa) { var board = new Piece[81]; for (int i = 0; i < 81; ++i) { board[i] = Piece.NO_PIECE; } var hand = new Hand[2]; for (int i = 0; i < 2; ++i) { hand[i] = Hand.ZERO; } Color turn = Color.BLACK; int ply = 1; // 盤面一括 Regex bRegex = new Regex(@"^P[1-9](?: \* |[+-](?:FU|KY|KE|GI|KI|KA|HI|OU|TO|NY|NK|NG|UM|RY)){9}"); // 駒個別 Regex hRegex = new Regex(@"^P[+-]((?:[0-9][0-9](?:FU|KY|KE|GI|KI|KA|HI|OU|TO|NY|NK|NG|UM|RY))+)"); foreach (var line in csa) { if (line.StartsWith("+")) { turn = Color.BLACK; break; } if (line.StartsWith("-")) { turn = Color.WHITE; break; } if (!line.StartsWith("P")) { continue; } if (line.StartsWith("PI")) { // 平手初期配置 for (int i = 0; i < 81; ++i) { board[i] = Piece.NO_PIECE; } board[Square.SQ_11.ToInt()] = Piece.W_LANCE; board[Square.SQ_21.ToInt()] = Piece.W_KNIGHT; board[Square.SQ_31.ToInt()] = Piece.W_SILVER; board[Square.SQ_41.ToInt()] = Piece.W_GOLD; board[Square.SQ_51.ToInt()] = Piece.W_KING; board[Square.SQ_61.ToInt()] = Piece.W_GOLD; board[Square.SQ_71.ToInt()] = Piece.W_SILVER; board[Square.SQ_81.ToInt()] = Piece.W_KNIGHT; board[Square.SQ_91.ToInt()] = Piece.W_LANCE; board[Square.SQ_22.ToInt()] = Piece.W_BISHOP; board[Square.SQ_82.ToInt()] = Piece.W_ROOK; board[Square.SQ_13.ToInt()] = Piece.W_PAWN; board[Square.SQ_23.ToInt()] = Piece.W_PAWN; board[Square.SQ_33.ToInt()] = Piece.W_PAWN; board[Square.SQ_43.ToInt()] = Piece.W_PAWN; board[Square.SQ_53.ToInt()] = Piece.W_PAWN; board[Square.SQ_63.ToInt()] = Piece.W_PAWN; board[Square.SQ_73.ToInt()] = Piece.W_PAWN; board[Square.SQ_83.ToInt()] = Piece.W_PAWN; board[Square.SQ_93.ToInt()] = Piece.W_PAWN; board[Square.SQ_17.ToInt()] = Piece.B_PAWN; board[Square.SQ_27.ToInt()] = Piece.B_PAWN; board[Square.SQ_37.ToInt()] = Piece.B_PAWN; board[Square.SQ_47.ToInt()] = Piece.B_PAWN; board[Square.SQ_57.ToInt()] = Piece.B_PAWN; board[Square.SQ_67.ToInt()] = Piece.B_PAWN; board[Square.SQ_77.ToInt()] = Piece.B_PAWN; board[Square.SQ_87.ToInt()] = Piece.B_PAWN; board[Square.SQ_97.ToInt()] = Piece.B_PAWN; board[Square.SQ_28.ToInt()] = Piece.B_ROOK; board[Square.SQ_88.ToInt()] = Piece.B_BISHOP; board[Square.SQ_19.ToInt()] = Piece.B_LANCE; board[Square.SQ_29.ToInt()] = Piece.B_KNIGHT; board[Square.SQ_39.ToInt()] = Piece.B_SILVER; board[Square.SQ_49.ToInt()] = Piece.B_GOLD; board[Square.SQ_59.ToInt()] = Piece.B_KING; board[Square.SQ_69.ToInt()] = Piece.B_GOLD; board[Square.SQ_79.ToInt()] = Piece.B_SILVER; board[Square.SQ_89.ToInt()] = Piece.B_KNIGHT; board[Square.SQ_99.ToInt()] = Piece.B_LANCE; // 駒落ちの検出 foreach (Match match in new Regex(@"^([1-9][1-9])(FU|KY|KE|GI|KI|KA|HI|OU)").Matches(line) ) { if (!match.Success) { continue; } File f = (File)(match.Groups[1].Value[0] - '1'); Rank r = (Rank)(match.Groups[1].Value[1] - '1'); Square sq = Util.MakeSquare(f, r); Piece pc = FromCsaPieceType(match.Groups[2].Value); // そのマスに指定された駒が無かったらおかしい if (board[sq.ToInt()].PieceType() != pc) { return(""); } board[sq.ToInt()] = Piece.NO_PIECE; } continue; } Match bMatch = bRegex.Match(line); if (bMatch.Success) { Rank r = (Rank)(bMatch.Groups[0].Value[1] - '1'); for (File f = File.FILE_9; f >= File.FILE_1; --f) { Piece pc = FromCsaPiece(bMatch.Groups[0].Value.Substring((int)(File.FILE_9 - f) * 3 + 2, 3)); board[Util.MakeSquare(f, r).ToInt()] = pc; } continue; } if (line.StartsWith("P+00AL")) { int[] restCount = { 99, 18, 4, 4, 4, 2, 2, 4, 2 }; foreach (Square sq in All.Squares()) { restCount[(int)board[(int)sq].RawPieceType()] -= 1; } for (Piece p = Piece.PAWN; p < Piece.KING; ++p) { restCount[p.ToInt()] -= hand[Color.BLACK.ToInt()].Count(p); restCount[p.ToInt()] -= hand[Color.WHITE.ToInt()].Count(p); hand[Color.BLACK.ToInt()].Add(p, SysMath.Max(restCount[p.ToInt()], 0)); } continue; } if (line.StartsWith("P-00AL")) { int[] restCount = { 99, 18, 4, 4, 4, 2, 2, 4, 2 }; foreach (Square sq in All.Squares()) { restCount[(int)board[(int)sq].RawPieceType()] -= 1; } for (Piece p = Piece.PAWN; p < Piece.KING; ++p) { restCount[p.ToInt()] -= hand[Color.BLACK.ToInt()].Count(p); restCount[p.ToInt()] -= hand[Color.WHITE.ToInt()].Count(p); hand[Color.WHITE.ToInt()].Add(p, SysMath.Max(restCount[p.ToInt()], 0)); } continue; } Match hMatch = hRegex.Match(line); if (hMatch.Success) { // 駒別単独表現 Color c = (hMatch.Groups[0].Value[1] != '-') ? Color.BLACK : Color.WHITE; string resGroup = hMatch.Groups[1].Value; for (int i = 0; i < resGroup.Length; i += 4) { File f = (File)(resGroup[i + 0] - '1'); Rank r = (Rank)(resGroup[i + 1] - '1'); Piece pc = FromCsaPieceType(resGroup.Substring(i + 2, 2)); if (f >= File.FILE_1 && r >= Rank.RANK_1) { board[Util.MakeSquare(f, r).ToInt()] = Util.MakePiece(c, pc); continue; } if (pc.IsPromote()) { return(""); } hand[c.ToInt()].Add(pc); } continue; } } return(Position.SfenFromRawdata(board, hand, turn, ply)); }
/** Return the interval in common between this and o */ public virtual Interval Intersection(Interval other) { return(Interval.Create(Math.Max(a, other.a), Math.Min(b, other.b))); }
/// <summary> /// Clamps the value to the allowed non-system (custom) priority range. /// </summary> /// <param name="value">The value to clamp.</param> /// <returns> /// The clamped value. /// (<see cref="MinPriority"/> <= clampedValue <= <see cref="MaxPriority"/> /// </returns> public static int ClampPriority(int value) { return(Math.Max(MinPriority, Math.Min(MaxPriority, value))); }
public void Update(float dt) { // Reset deltas MovementNormalizedDelta = new Float4(0.0f); MovementRawDelta = new Float4(0.0f); MovementDirectDelta = new Float4(0.0f); RotationDelta = new Float4(0.0f); RotationQuaternionDelta = Quaternion.Default; ScaleDelta = new Float4(0.0f); FovDelta = 0.0f; MovementNormalizedLength = 0.0f; if (ActiveMapping != null) { foreach (var input in ActiveMapping.KeyInputs) { if (CheckKeyInput(input.Key, input.Type)) { // Skip single keys if there is a combo key input active bool skipKey = false; foreach (var comboKeyInput in ActiveMapping.ComboKeyInputs.Where(x => x.ConsumeInput && (x.Key1 == input.Key || x.Key2 == input.Key))) { var key = comboKeyInput.Key1 == input.Key ? comboKeyInput.Key2 : comboKeyInput.Key1; var type = comboKeyInput.Key1 == input.Key ? comboKeyInput.Type2 : comboKeyInput.Type1; if (CheckKeyInput(key, type)) { skipKey = true; break; } } if (skipKey) { continue; } input.Action.Execute(); } } foreach (var input in ActiveMapping.ComboKeyInputs) { if (CheckKeyInput(input.Key1, input.Type1) && CheckKeyInput(input.Key2, input.Type2)) { input.Action.Execute(); } } foreach (var input in ActiveMapping.MouseInputs) { if (CheckMouseInput(input.Key, input.Type)) { input.Action.Execute(); } } foreach (var input in ActiveMapping.ScrollInputs) { if (CheckScrollInput(input.Key)) { input.Action.Execute(); } } if (CaptureMouse) { Float2 mouseDiff = Application.GetCursorDiff(true); foreach (var input in ActiveMapping.MouseAxisInputs) { float length = input.Axis.Dot(mouseDiff); if (Math.Abs(length) > Constants.Epsilon) { if (input.Action is InputMovementAction movementAction) { // Copy of the InputMovementAction.Execute function but multiplied with length for mouse input var vector = movementAction.GetVector() * length; MovementRawDelta += vector; if (movementAction.Normalize) { MovementNormalizedLength = Math.Max(vector.Length(), MovementNormalizedLength); } else { MovementDirectDelta += vector; } } else if (input.Action is InputRotationAction rotationAction) { RotationDelta += rotationAction.GetRotation() * length; // TODO: move dt to UpdateEntities RotationQuaternionDelta *= rotationAction.GetQuaternion(length * dt); } else if (input.Action is InputScalingAction scaleAction) { ScaleDelta += scaleAction.GetVector() * length; } else { input.Action.Execute(); } } } } } MovementNormalizedDelta += MovementRawDelta.Normalize() * MovementNormalizedLength; UpdateEntities(dt); }
public void Generate(Pawn mother = null, Pawn father = null) { int RandSeed = 0; if (MP.IsInMultiplayer) { Rand.PushState(); RandSeed = Rand.RangeInclusive(-100000, 100000); Rand.PopState(); } if (!(parent is Pawn pawn)) { return; } if (!Genes.EffectsThing(parent)) { return; } _geneRecords = new Dictionary <StatDef, GeneRecord>(); if (mother == null) { mother = pawn.GetMother(); } if (father == null) { father = pawn.GetFather(); } var motherStats = mother?.AnimalGenetics().GeneRecords; var fatherStats = father?.AnimalGenetics().GeneRecords; var affectedStats = Constants.affectedStats; foreach (var stat in affectedStats) { if (MP.IsInMultiplayer) { Rand.PushState(RandSeed); } float motherValue = motherStats != null ? motherStats[stat].Value : Mathf.Max(Verse.Rand.Gaussian(Settings.Core.mean, Settings.Core.stdDev), 0.1f); float fatherValue = fatherStats != null ? fatherStats[stat].Value : Mathf.Max(Verse.Rand.Gaussian(Settings.Core.mean, Settings.Core.stdDev), 0.1f); float highValue = Math.Max(motherValue, fatherValue); float lowValue = Math.Min(motherValue, fatherValue); float?ToNullableFloat(bool nullify, float value) => nullify ? null : (float?)value; var record = new GeneRecord(ToNullableFloat(mother == null, motherValue), ToNullableFloat(father == null, fatherValue)); record.ParentValue = Verse.Rand.Chance(Settings.Core.bestGeneChance) ? highValue : lowValue; if (record.ParentValue == motherValue) { record.Parent = motherStats != null ? GeneRecord.Source.Mother : GeneRecord.Source.None; } else { record.Parent = fatherStats != null ? GeneRecord.Source.Father : GeneRecord.Source.None; } record.Value = record.ParentValue + Verse.Rand.Gaussian(Settings.Core.mutationMean, Settings.Core.mutationStdDev); record.Value = Mathf.Max(record.Value, 0.1f); _geneRecords[stat] = record; if (MP.IsInMultiplayer) { Rand.PopState(); RandSeed += 1; } } }
public void Shift(Vector delta) { if (delta.X == 0 && delta.Y == 0 && AbsoluteCenterCoordinates != null) { return; } CenterCoordinates = CenterCoordinates.Shift(delta.X, delta.Y, Rotation, ArcSecWidth, ArcSecHeight); AbsoluteCenterCoordinates = new Coordinates(CenterCoordinates.RADegrees, Math.Abs(CenterCoordinates.Dec), Epoch.J2000, Coordinates.RAType.Degrees); TopCenter = AbsoluteCenterCoordinates.Shift(0, -OriginalVFoV / 2, 0); TopLeft = AbsoluteCenterCoordinates.Shift(-OriginalHFoV / 2, (-OriginalVFoV / 2), 0); BottomLeft = AbsoluteCenterCoordinates.Shift(-OriginalHFoV / 2, (OriginalVFoV / 2), 0); BottomCenter = AbsoluteCenterCoordinates.Shift(0, OriginalVFoV / 2, 0); VFoVDegTop = Math.Abs(Math.Max(TopCenter.Dec, TopLeft.Dec) - AbsoluteCenterCoordinates.Dec); VFoVDegBottom = Math.Abs(AbsoluteCenterCoordinates.Dec - Math.Min(BottomLeft.Dec, BottomCenter.Dec)); HFoVDeg = TopLeft.RADegrees > TopCenter.RADegrees ? TopLeft.RADegrees - TopCenter.RADegrees : TopLeft.RADegrees - TopCenter.RADegrees + 360; HFoVDeg *= 2; // if we're below 0 we need to flip all calculated decs if (CenterCoordinates.Dec < 0) { BottomLeft.Dec *= -1; TopLeft.Dec *= -1; TopCenter.Dec *= -1; BottomCenter.Dec *= -1; AboveZero = false; } else { AboveZero = true; } // if the top center ra is different than the center coordinate ra then the top center point is above 90deg if (Math.Abs(TopCenter.RADegrees - CenterCoordinates.RADegrees) > 0.0001) { // horizontal fov becomes 360 here and vertical fov the difference between center and 90deg HFoVDeg = 360; VFoVDegTop = 90 - AbsoluteCenterCoordinates.Dec; IsAbove90 = true; } else { IsAbove90 = false; } AbsCalcTopDec = AbsoluteCenterCoordinates.Dec + VFoVDegTop; AbsCalcBottomDec = AbsoluteCenterCoordinates.Dec - VFoVDegBottom; if (AboveZero) { CalcTopDec = CenterCoordinates.Dec + VFoVDegTop; CalcBottomDec = CenterCoordinates.Dec - VFoVDegBottom; } else { CalcTopDec = CenterCoordinates.Dec - VFoVDegTop; CalcBottomDec = CenterCoordinates.Dec + VFoVDegBottom; } CalcRAMax = TopLeft.RADegrees; CalcRAMin = CalcRAMax - HFoVDeg; if (CalcRAMin < 0) { CalcRAMin += 360; } }
/* * ConvertToBezierForm : * Given a point and a Bezier curve, generate a 5th-degree * Bezier-format equation whose solution finds the point on the * curve nearest the user-defined point. * P; The point to find t for * V; The control points */ static Point[] ConvertToBezierForm(Point P, Point[] V) { int i, j, k, m, n, ub, lb; int row, column; /* Table indices */ Point[] c = new Point[DEGREE + 1]; /* V(i)'s - P */ Point[] d = new Point[DEGREE]; /* V(i+1) - V(i) */ Point[] w; /* Ctl pts of 5th-degree curve */ double[,] cdTable = new double[3, 4]; /* Dot product of c, d */ /*Determine the c's -- these are vectors created by subtracting*/ /* point P from each of the control points */ for (i = 0; i <= DEGREE; i++) { V2Sub(V[i], P, ref c[i]); } /* Determine the d's -- these are vectors created by subtracting*/ /* each control point from the next */ for (i = 0; i <= DEGREE - 1; i++) { d[i] = V2ScaleII(V2Sub(V[i + 1], V[i], ref d[i]), 3.0); } /* Create the c,d table -- this is a table of dot products of the */ /* c's and d's */ for (row = 0; row <= DEGREE - 1; row++) { for (column = 0; column <= DEGREE; column++) { cdTable[row, column] = V2Dot(d[row], c[column]); } } /* Now, apply the z's to the dot products, on the skew diagonal*/ /* Also, set up the x-values, making these "points" */ w = new Point[W_DEGREE + 1]; // Point *)malloc((unsigned)(W_DEGREE+1) * sizeof(Point)); for (i = 0; i <= W_DEGREE; i++) { // w[i].Y = 0.0; // w[i].X = (double)(i) / W_DEGREE; w[i] = new Point((double)(i) / W_DEGREE, 0.0); } n = DEGREE; m = DEGREE - 1; for (k = 0; k <= n + m; k++) { lb = Math.Max(0, k - m); ub = Math.Min(k, n); for (i = lb; i <= ub; i++) { j = k - i; // w[i + j].Y += cdTable[j, i] * z[j, i]; var old = w[i + j]; w[i + j] = new Point(old.X, old.Y + cdTable[j, i] * z[j, i]); } } return(w); }
public static int Clamp(int value, int min, int max) { return(SMath.Min(SMath.Max(value, min), max)); }
/// <summary> /// {@inheritDoc} /// </summary> /// <exception cref="ConvergenceException"> if the algorithm failed due to finite /// precision. </exception> protected internal override sealed double DoSolve() { // Get initial solution double x0 = this.Min; double x1 = this.Max; double f0 = this.ComputeObjectiveValue(x0); double f1 = this.ComputeObjectiveValue(x1); // If one of the bounds is the exact root, return it. Since these are // not under-approximations or over-approximations, we can return them // regardless of the allowed solutions. if (f0 == 0.0) { return(x0); } if (f1 == 0.0) { return(x1); } // Verify bracketing of initial solution. this.VerifyBracketing(x0, x1); // Get accuracies. double ftol = this.FunctionValueAccuracy; double atol = this.AbsoluteAccuracy; double rtol = this.RelativeAccuracy; // Keep track of inverted intervals, meaning that the left bound is // larger than the right bound. bool inverted = false; // Keep finding better approximations. while (true) { // Calculate the next approximation. double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0)); double fx = this.ComputeObjectiveValue(x); // If the new approximation is the exact root, return it. Since // this is not an under-approximation or an over-approximation, // we can return it regardless of the allowed solutions. if (fx == 0.0) { return(x); } // Update the bounds with the new approximation. if (f1 * fx < 0) { // The value of x1 has switched to the other bound, thus inverting // the interval. x0 = x1; f0 = f1; inverted = !inverted; } else { switch (this.method) { case BaseSecantSolver.Method.ILLINOIS: f0 *= 0.5; break; case BaseSecantSolver.Method.PEGASUS: f0 *= f1 / (f1 + fx); break; case Method.REGULA_FALSI: // Detect early that algorithm is stuck, instead of waiting // for the maximum number of iterations to be exceeded. if (x == x1) { throw new ConvergenceException(); } break; default: // Should never happen. throw new MathInternalError(); } } // Update from [x0, x1] to [x0, x]. x1 = x; f1 = fx; // If the function value of the last approximation is too small, // given the function value accuracy, then we can't get closer to // the root than we already are. if (FastMath.Abs(f1) <= ftol) { switch (this.allowed) { case AllowedSolution.ANY_SIDE: return(x1); case AllowedSolution.LEFT_SIDE: if (inverted) { return(x1); } break; case AllowedSolution.RIGHT_SIDE: if (!inverted) { return(x1); } break; case AllowedSolution.BELOW_SIDE: if (f1 <= 0) { return(x1); } break; case AllowedSolution.ABOVE_SIDE: if (f1 >= 0) { return(x1); } break; default: throw new MathInternalError(); } } // If the current interval is within the given accuracies, we // are satisfied with the current approximation. if (FastMath.Abs(x1 - x0) < FastMath.Max(rtol * FastMath.Abs(x1), atol)) { switch (this.allowed) { case AllowedSolution.ANY_SIDE: return(x1); case AllowedSolution.LEFT_SIDE: return(inverted ? x1 : x0); case AllowedSolution.RIGHT_SIDE: return(inverted ? x0 : x1); case AllowedSolution.BELOW_SIDE: return((f1 <= 0) ? x1 : x0); case AllowedSolution.ABOVE_SIDE: return((f1 >= 0) ? x1 : x0); default: throw new MathInternalError(); } } } }
public static float Clamp(float value, float min, float max) { return(SMath.Min(SMath.Max(value, min), max)); }
/** * Grows the set to a larger number of bits. * @param bit element that must fit in set */ public virtual void GrowToInclude(int bit) { int newSize = Math.Max(_bits.Length << 1, NumWordsToHold(bit)); Array.Resize(ref _bits, newSize); }
/// <summary> /// {@inheritDoc} /// </summary> protected internal override double DoSolve() { double min = this.Min; double max = this.Max; // [x1, x2] is the bracketing interval in each iteration // x3 is the midpoint of [x1, x2] // x is the new root approximation and an endpoint of the new interval double x1 = min; double y1 = this.ComputeObjectiveValue(x1); double x2 = max; double y2 = this.ComputeObjectiveValue(x2); // check for zeros before verifying bracketing if (y1 == 0) { return(min); } if (y2 == 0) { return(max); } this.VerifyBracketing(min, max); double absoluteAccuracy = this.AbsoluteAccuracy; double functionValueAccuracy = this.FunctionValueAccuracy; double relativeAccuracy = this.RelativeAccuracy; double oldx = double.PositiveInfinity; while (true) { // calculate the new root approximation double x3 = 0.5 * (x1 + x2); double y3 = this.ComputeObjectiveValue(x3); if (FastMath.Abs(y3) <= functionValueAccuracy) { return(x3); } double delta = 1 - (y1 * y2) / (y3 * y3); // delta > 1 due to bracketing double correction = (MyUtils.Signum(y2) * MyUtils.Signum(y3)) * (x3 - x1) / FastMath.Sqrt(delta); double x = x3 - correction; // correction != 0 double y = this.ComputeObjectiveValue(x); // check for convergence double tolerance = FastMath.Max(relativeAccuracy * FastMath.Abs(x), absoluteAccuracy); if (FastMath.Abs(x - oldx) <= tolerance) { return(x); } if (FastMath.Abs(y) <= functionValueAccuracy) { return(x); } // prepare the new interval for next iteration // Ridders' method guarantees x1 < x < x2 if (correction > 0.0) // x1 < x < x3 { if (MyUtils.Signum(y1) + MyUtils.Signum(y) == 0.0) { x2 = x; y2 = y; } else { x1 = x; x2 = x3; y1 = y; y2 = y3; } } // x3 < x < x2 else { if (MyUtils.Signum(y2) + MyUtils.Signum(y) == 0.0) { x1 = x; y1 = y; } else { x1 = x3; x2 = x; y1 = y3; y2 = y; } } oldx = x; } }
public static float clamp(float x, float min, float max) { return(Math.Max(Math.Min(x, max), min)); }
/** <summary>Grows the set to a larger number of bits.</summary> * <param name="bit">element that must fit in set</param> */ public void GrowToInclude(int bit) { int newSize = Math.Max(_bits.Length << 1, NumWordsToHold(bit)); SetSize(newSize); }
static public int Distance_King(int x1, int y1, int x2, int y2) { return(SMath.Max(SMath.Abs(x1 - x2), SMath.Abs(y1 - y2))); }
public void Initialize() { // Heightmap Map to water level creation ( only required for water ) //--------------------------------------------------------------------- if (underwaterHeightView != null) { underwaterHeightView.Dispose(); } if (normalView != null) { normalView.Dispose(); } Texture2DDescription descHM = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R8_UNorm, Width = info.width, Height = info.height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), Usage = ResourceUsage.Staging, }; Texture2D MappableTexture = new Texture2D(Display.device, descHM); Surface surf = MappableTexture.QueryInterface <Surface>(); DataStream stream; DataRectangle rect = surf.Map(SharpDX.DXGI.MapFlags.Write, out stream); stream.Position = 0; float delta = 1; //float level_clean = saturate((level-0.95f)/(1-0.95f)); for (int y = 0; y < info.height; y++) { for (int x = 0; x < info.width; x++) { float val = ((info.altitudeData[x, y] - (info.waterLevel - delta)) / delta); stream.WriteByte((byte)GameUtils.Clamp(val * 255, 0, 255)); } } surf.Unmap(); var desc = new Texture2DDescription(); desc.Width = info.width; desc.Height = info.height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = SharpDX.DXGI.Format.R8_UNorm; desc.Usage = ResourceUsage.Default; desc.BindFlags = BindFlags.ShaderResource; desc.CpuAccessFlags = CpuAccessFlags.None; desc.SampleDescription = new SampleDescription(1, 0); Texture2D newText = new Texture2D(Display.device, desc); Display.context.CopyResource(MappableTexture, newText); MappableTexture.Dispose(); underwaterHeightView = new ShaderResourceView(Display.device, newText); // Normal Map creation //--------------------------------------------------------------------- descHM = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R8G8B8A8_UNorm, Width = info.width, Height = info.height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), Usage = ResourceUsage.Staging, }; MappableTexture = new Texture2D(Display.device, descHM); surf = MappableTexture.QueryInterface <Surface>(); DataStream streamN; rect = surf.Map(SharpDX.DXGI.MapFlags.Write, out streamN); streamN.Position = 0; for (int y = 0; y < info.height; y++) { for (int x = 0; x < info.width; x++) { Vector3 data = info.normalData[x, y]; data.X = Math.Abs(data.X); data.Y = Math.Max(data.Y, 0); data.Z = Math.Abs(data.Z); data.X = GameUtils.Clamp(data.X * 255, 0, 255); data.Y = GameUtils.Clamp(data.Y * 255, 0, 255); data.Z = GameUtils.Clamp(data.Z * 255, 0, 255); streamN.WriteByte((byte)(data.X)); streamN.WriteByte((byte)(data.Y)); streamN.WriteByte((byte)(data.Z)); streamN.WriteByte(0xFF); } } surf.Unmap(); desc = new Texture2DDescription(); desc.Width = info.width; desc.Height = info.height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm; desc.Usage = ResourceUsage.Default; desc.BindFlags = BindFlags.ShaderResource; desc.CpuAccessFlags = CpuAccessFlags.None; desc.SampleDescription = new SampleDescription(1, 0); newText = new Texture2D(Display.device, desc); Display.context.CopyResource(MappableTexture, newText); MappableTexture.Dispose(); normalView = new ShaderResourceView(Display.device, newText); }
/// <summary> /// Resizes the text for the given width/height. /// </summary> /// <param name="width">The available width in pixel.</param> /// <param name="height">The available height in pixel.</param> private void ResizeText(int width, int height) { // cast the c# string into a Java CharSequence so it works with the native methods var text = CharSequence.ArrayFromStringArray(new[] { Control.Text })[0]; // Do not resize if the view does not have dimensions or there is no text if (text == null || text.Length() == 0 || height <= 0 || width <= 0 || Math.Abs(_textSize) < 0.1) { return; } if (Control.TransformationMethod != null) { text = Control.TransformationMethod.GetTransformationFormatted(text, this); } // Get the text view's paint object var textPaint = Control.Paint; // If there is a max text size set, use the lesser of that and the default text size var targetTextSize = _maxTextSize > 0 ? Math.Min(_textSize, _maxTextSize) : _textSize; // Get the maximal text height var layout = GetTextLayout(text, textPaint, width, targetTextSize); // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes while ((layout.Height > height || layout.LineCount > _maxLines) && targetTextSize > _minTextSize) { targetTextSize = Math.Max(targetTextSize - 2, _minTextSize); layout = GetTextLayout(text, textPaint, width, targetTextSize); } // If we had reached our minimum text size and still don't fit, append an ellipsis if (Math.Abs(targetTextSize - _minTextSize) < 1 && layout.Height > height) { targetTextSize = _minTextSize; var end = text.Length(); var newText = CharSequence.ArrayFromStringArray(new[] { text.SubSequence(0, end) + "..." })[0]; layout = GetTextLayout(newText, textPaint, width, targetTextSize); // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes while (layout.Height > height || layout.LineCount > _maxLines) { end -= 1; if (end < 1) { break; } newText = CharSequence.ArrayFromStringArray(new[] { text.SubSequence(0, end) + "..." })[0]; layout = GetTextLayout(newText, textPaint, width, targetTextSize); } Control.SetText(text.SubSequence(0, end) + "...", TextView.BufferType.Normal); } // finally set the text size we calculated SetTextSize(targetTextSize); // Reset force resize flag _needsResizing = false; }
/// <summary> /// Lerp the specified a, b and t. /// </summary> /// <returns>The lerp.</returns> /// <param name="a">The alpha component.</param> /// <param name="b">The blue component.</param> /// <param name="t">T.</param> public static DVector2 Lerp(DVector2 a, DVector2 b, double t) { double s = M.Max(0, M.Min(t, 1)); return(a * (1 - s) + b * s); }
/** Given the set of possible values (rather than, say UNICODE or MAXINT), * return a new set containing all elements in vocabulary, but not in * this. The computation is (vocabulary - this). * * 'this' is assumed to be either a subset or equal to vocabulary. */ public virtual IntervalSet Complement(Interval vocabulary) { if (vocabulary.EndInclusive < MinElement || vocabulary.Start > MaxElement) { // nothing in common with this set return(null); } int n = intervals.Count; if (n == 0) { return(IntervalSet.Of(vocabulary)); } IntervalSet compl = new IntervalSet(); Interval first = intervals[0]; // add a range from 0 to first.Start constrained to vocab if (first.Start > vocabulary.Start) { compl.Intervals.Add(Interval.FromBounds(vocabulary.Start, first.Start - 1)); } for (int i = 1; i < n; i++) { if (intervals[i - 1].EndInclusive >= vocabulary.EndInclusive) { break; } if (intervals[i].Start <= vocabulary.Start) { continue; } if (intervals[i - 1].EndInclusive == intervals[i].Start - 1) { continue; } compl.Intervals.Add(Interval.FromBounds(Math.Max(vocabulary.Start, intervals[i - 1].EndInclusive + 1), Math.Min(vocabulary.EndInclusive, intervals[i].Start - 1))); //// from 2nd interval .. nth //Interval previous = intervals[i - 1]; //Interval current = intervals[i]; //IntervalSet s = IntervalSet.Of( previous.EndInclusive + 1, current.Start - 1 ); //IntervalSet a = (IntervalSet)s.And( vocabularyIS ); //compl.AddAll( a ); } Interval last = intervals[n - 1]; // add a range from last.EndInclusive to maxElement constrained to vocab if (last.EndInclusive < vocabulary.EndInclusive) { compl.Intervals.Add(Interval.FromBounds(last.EndInclusive + 1, vocabulary.EndInclusive)); //IntervalSet s = IntervalSet.Of( last.EndInclusive + 1, maxElement ); //IntervalSet a = (IntervalSet)s.And( vocabularyIS ); //compl.AddAll( a ); } return(compl); }
VisualElement writeHead; //The microphone writing position in the audio clip public static int Clamp(int a, int min, int max) { return(Math.Max(Math.Min(a, max), min)); }