//----------------------------------------------------------------------------- // Purpose: Think while actively tracking a target. //----------------------------------------------------------------------------- void CNPC_CombineCamera::ActiveThink() { // Allow descended classes a chance to do something before the think function if (PreThink(CAMERA_ACTIVE)) return; // No active target, look for suspicious characters. CBaseEntity *pTarget = MaintainEnemy(); if ( !pTarget ) { // Nobody suspicious. Go back to being idle. m_hEnemyTarget = NULL; EmitSound("NPC_CombineCamera.BecomeIdle"); SetAngry(false); SetThink(&CNPC_CombineCamera::SearchThink); SetNextThink( gpGlobals->curtime ); return; } // Examine the target until it reaches our inner radius if ( pTarget != m_hEnemyTarget ) { Vector vecDelta = pTarget->GetAbsOrigin() - GetAbsOrigin(); float flDist = vecDelta.Length(); if ( (flDist < m_nInnerRadius) && FInViewCone(pTarget) ) { m_OnFoundEnemy.Set(pTarget, pTarget, this); // If it's a citizen, it's ok. If it's the player, it's not ok. if ( pTarget->IsPlayer() ) { SetEyeState(CAMERA_EYE_FOUND_TARGET); if (HasSpawnFlags(SF_COMBINE_CAMERA_BECOMEANGRY)) { SetAngry(true); } else { EmitSound("NPC_CombineCamera.Active"); } m_OnFoundPlayer.Set(pTarget, pTarget, this); m_hEnemyTarget = pTarget; } else { SetEyeState(CAMERA_EYE_HAPPY); m_flEyeHappyTime = gpGlobals->curtime + 2.0; // Now forget about this target forever AddEntityRelationship( pTarget, D_NU, 99 ); } } else { // If we get angry automatically, we get un-angry automatically if ( HasSpawnFlags(SF_COMBINE_CAMERA_BECOMEANGRY) && m_bAngry ) { SetAngry(false); } m_hEnemyTarget = NULL; // We don't quite see this guy, but we sense him. SetEyeState(CAMERA_EYE_SEEKING_TARGET); } } // Update our think time SetNextThink( gpGlobals->curtime + 0.1f ); TrackTarget(pTarget); MaintainEye(); }
void LocaleWin::initializeLocalizerData() { if (m_didInitializeNumberData) return; Vector<String, DecimalSymbolsSize> symbols; enum DigitSubstitution { DigitSubstitutionContext = 0, DigitSubstitution0to9 = 1, DigitSubstitutionNative = 2, }; DWORD digitSubstitution = DigitSubstitution0to9; getLocaleInfo(LOCALE_IDIGITSUBSTITUTION, digitSubstitution); if (digitSubstitution == DigitSubstitution0to9) { symbols.append("0"); symbols.append("1"); symbols.append("2"); symbols.append("3"); symbols.append("4"); symbols.append("5"); symbols.append("6"); symbols.append("7"); symbols.append("8"); symbols.append("9"); } else { String digits = getLocaleInfoString(LOCALE_SNATIVEDIGITS); ASSERT(digits.length() >= 10); for (unsigned i = 0; i < 10; ++i) symbols.append(digits.substring(i, 1)); } ASSERT(symbols.size() == DecimalSeparatorIndex); symbols.append(getLocaleInfoString(LOCALE_SDECIMAL)); ASSERT(symbols.size() == GroupSeparatorIndex); symbols.append(getLocaleInfoString(LOCALE_STHOUSAND)); ASSERT(symbols.size() == DecimalSymbolsSize); String negativeSign = getLocaleInfoString(LOCALE_SNEGATIVESIGN); enum NegativeFormat { NegativeFormatParenthesis = 0, NegativeFormatSignPrefix = 1, NegativeFormatSignSpacePrefix = 2, NegativeFormatSignSuffix = 3, NegativeFormatSpaceSignSuffix = 4, }; DWORD negativeFormat = NegativeFormatSignPrefix; getLocaleInfo(LOCALE_INEGNUMBER, negativeFormat); String negativePrefix = emptyString(); String negativeSuffix = emptyString(); switch (negativeFormat) { case NegativeFormatParenthesis: negativePrefix = "("; negativeSuffix = ")"; break; case NegativeFormatSignSpacePrefix: negativePrefix = negativeSign + " "; break; case NegativeFormatSignSuffix: negativeSuffix = negativeSign; break; case NegativeFormatSpaceSignSuffix: negativeSuffix = " " + negativeSign; break; case NegativeFormatSignPrefix: // Fall through. default: negativePrefix = negativeSign; break; } m_didInitializeNumberData = true; setLocalizerData(symbols, emptyString(), emptyString(), negativePrefix, negativeSuffix); }
static bool writeUInt16(Vector<char>& vector, uint16_t value) { uint16_t bigEndianValue = htons(value); return vector.tryAppend(reinterpret_cast<char*>(&bigEndianValue), sizeof(bigEndianValue)); }
void SMILTimeContainer::sortByPriority(Vector<SVGSMILElement*>& smilElements, SMILTime elapsed) { if (m_documentOrderIndexesDirty) updateDocumentOrderIndexes(); std::sort(smilElements.begin(), smilElements.end(), PriorityCompare(elapsed)); }
// See http://msdn.microsoft.com/en-us/library/dd317787(v=vs.85).aspx static Vector<DateFormatToken> parseDateFormat(const String format) { Vector<DateFormatToken> tokens; StringBuilder literalBuffer; bool inQuote = false; bool lastQuoteCanBeLiteral = false; for (unsigned i = 0; i < format.length(); ++i) { UChar ch = format[i]; if (inQuote) { if (ch == '\'') { inQuote = false; ASSERT(i); if (lastQuoteCanBeLiteral && format[i - 1] == '\'') { literalBuffer.append('\''); lastQuoteCanBeLiteral = false; } else lastQuoteCanBeLiteral = true; } else literalBuffer.append(ch); continue; } if (ch == '\'') { inQuote = true; if (lastQuoteCanBeLiteral && i > 0 && format[i - 1] == '\'') { literalBuffer.append(ch); lastQuoteCanBeLiteral = false; } else lastQuoteCanBeLiteral = true; } else if (isYearSymbol(ch)) { commitLiteralToken(literalBuffer, tokens); unsigned count = countContinuousLetters(format, i); i += count - 1; if (count == 1) tokens.append(DateFormatToken(DateFormatToken::Year1)); else if (count == 2) tokens.append(DateFormatToken(DateFormatToken::Year2)); else tokens.append(DateFormatToken(DateFormatToken::Year4)); } else if (isMonthSymbol(ch)) { commitLiteralToken(literalBuffer, tokens); unsigned count = countContinuousLetters(format, i); i += count - 1; if (count == 1) tokens.append(DateFormatToken(DateFormatToken::Month1)); else if (count == 2) tokens.append(DateFormatToken(DateFormatToken::Month2)); else if (count == 3) tokens.append(DateFormatToken(DateFormatToken::Month3)); else tokens.append(DateFormatToken(DateFormatToken::Month4)); } else if (isDaySymbol(ch)) { commitLiteralToken(literalBuffer, tokens); unsigned count = countContinuousLetters(format, i); i += count - 1; if (count == 1) tokens.append(DateFormatToken(DateFormatToken::Day1)); else tokens.append(DateFormatToken(DateFormatToken::Day2)); } else if (isEraSymbol(ch)) { // Just ignore era. // HTML5 date supports only A.D. } else literalBuffer.append(ch); } commitLiteralToken(literalBuffer, tokens); return tokens; }
int main(int argc, char *argv[]){ Network yarp; //Port<Bottle> armPlan; //Port<Bottle> armPred; Port armPlan; Port armPred; armPlan.open("/randArm/plan"); armPred.open("/randArm/pred"); bool fwCvOn = 0; fwCvOn = Network::connect("/randArm/plan","/fwdConv:i"); fwCvOn *= Network::connect("/fwdConv:o","/randArm/pred"); if (!fwCvOn){ printf("Please run command:\n ./fwdConv --input /fwdConv:i --output /fwdConv:o"); return 1; } const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); Property params; params.fromCommand(argc,argv); if (!params.check("robot")){ fprintf(stderr, "Please specify robot name"); fprintf(stderr, "e.g. --robot icub"); return -1; } std::string robotName = params.find("robot").asString().c_str(); std::string remotePorts = "/"; remotePorts += robotName; remotePorts += "/"; if (params.check("side")){ remotePorts += params.find("side").asString().c_str(); } else{ remotePorts += "left"; } remotePorts += "_arm"; std::string localPorts = "/randArm/cmd"; Property options; options.put("device", "remote_controlboard"); options.put("local", localPorts.c_str()); options.put("remote", remotePorts.c_str()); PolyDriver robotDevice(options); if (!robotDevice.isValid()){ printf("Device not available. Here are known devices: \n"); printf("%s", Drivers::factory().toString().c_str()); Network::fini(); return 1; } IPositionControl *pos; IEncoders *enc; bool ok; ok = robotDevice.view(pos); ok = ok && robotDevice.view(enc); if (!ok){ printf("Problems acquiring interfaces\n"); return 0; } int nj = 0; pos->getAxes(&nj); Vector encoders; Vector command; Vector commandCart; Vector tmp; encoders.resize(nj); tmp.resize(nj); command.resize(nj); commandCart.resize(nj); for (int i = 0; i < nj; i++) { tmp[i] = 25.0; } pos->setRefAccelerations(tmp.data()); for (int i = 0; i < nj; i++) { tmp[i] = 5.0; pos->setRefSpeed(i, tmp[i]); } command = 0; //set the arm joints to "middle" values command[0] = -45; command[1] = 45; command[2] = 0; command[3] = 45; pos->positionMove(command.data()); bool done = false; while (!done){ pos->checkMotionDone(&done); Time::delay(0.1); } while (true){ tmp = command; command[0] += 15*(2*gsl_rng_uniform(r)-1); command[1] += 15*(2*gsl_rng_uniform(r)-1); command[2] += 15*(2*gsl_rng_uniform(r)-1); command[3] += 15*(2*gsl_rng_uniform(r)-1); printf("%.1lf %.1lf %.1lf %.1lf\n", command[0], command[1], command[2], command[3]); //above 0 doesn't seem to be safe for joint 0 if (command[0] > 0 || command[0] < -90){ command[0] = tmp[0]; } if (command[1] > 160 || command[1] < -0){ command[1] = tmp[1]; } if (command[2] > 100 || command[2] < -35){ command[2] = tmp[2]; } if (command[3] > 100 || command[3] < 10){ command[3] = tmp[3]; } //use fwd kin to find end effector position Bottle plan, pred; for (int i = 0; i < nj; i++){ plan.add(command[i]); } armPlan.write(plan); armPred.read(pred); for (int i = 0; i < 3; i++){ commandCart[i] = pred.get(i).asDouble(); } double rad = sqrt(commandCart[0]*commandCart[0]+commandCart[1]*commandCart[1]); // safety radius back to 30 cm if (rad > 0.3){ pos->positionMove(command.data()); done = false; while(!done){ pos->checkMotionDone(&done); Time::delay(0.1); } } else{ printf("Self collision detected!\n"); } } robotDevice.close(); gsl_rng_free(r); return 0; }
void TextureMapperLayer::setChildren(const Vector<TextureMapperLayer*>& newChildren) { removeAllChildren(); for (size_t i = 0; i < newChildren.size(); ++i) addChild(newChildren[i]); }
TEST_F(AnimationInterpolationEffectTest, MultipleInterpolations) { InterpolationEffect interpolationEffect; interpolationEffect.addInterpolation(SampleInterpolation::create(InterpolableNumber::create(10), InterpolableNumber::create(15)), RefPtr<TimingFunction>(), 1, 2, 1, 3); interpolationEffect.addInterpolation(SampleInterpolation::create(InterpolableNumber::create(0), InterpolableNumber::create(1)), LinearTimingFunction::shared(), 0, 1, 0, 1); interpolationEffect.addInterpolation(SampleInterpolation::create(InterpolableNumber::create(1), InterpolableNumber::create(6)), CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease), 0.5, 1.5, 0.5, 1.5); Vector<RefPtr<Interpolation>> activeInterpolations; interpolationEffect.getActiveInterpolations(-0.5, duration, activeInterpolations); EXPECT_EQ(0ul, activeInterpolations.size()); interpolationEffect.getActiveInterpolations(0, duration, activeInterpolations); EXPECT_EQ(1ul, activeInterpolations.size()); EXPECT_FLOAT_EQ(0, getInterpolableNumber(activeInterpolations.at(0))); interpolationEffect.getActiveInterpolations(0.5, duration, activeInterpolations); EXPECT_EQ(2ul, activeInterpolations.size()); EXPECT_FLOAT_EQ(0.5f, getInterpolableNumber(activeInterpolations.at(0))); EXPECT_FLOAT_EQ(1, getInterpolableNumber(activeInterpolations.at(1))); interpolationEffect.getActiveInterpolations(1, duration, activeInterpolations); EXPECT_EQ(2ul, activeInterpolations.size()); EXPECT_FLOAT_EQ(10, getInterpolableNumber(activeInterpolations.at(0))); EXPECT_FLOAT_EQ(5.0282884f, getInterpolableNumber(activeInterpolations.at(1))); interpolationEffect.getActiveInterpolations(1, duration * 1000, activeInterpolations); EXPECT_EQ(2ul, activeInterpolations.size()); EXPECT_FLOAT_EQ(10, getInterpolableNumber(activeInterpolations.at(0))); EXPECT_FLOAT_EQ(5.0120168f, getInterpolableNumber(activeInterpolations.at(1))); interpolationEffect.getActiveInterpolations(1.5, duration, activeInterpolations); EXPECT_EQ(1ul, activeInterpolations.size()); EXPECT_FLOAT_EQ(12.5f, getInterpolableNumber(activeInterpolations.at(0))); interpolationEffect.getActiveInterpolations(2, duration, activeInterpolations); EXPECT_EQ(1ul, activeInterpolations.size()); EXPECT_FLOAT_EQ(15, getInterpolableNumber(activeInterpolations.at(0))); }
/// Construct q Quaternion from the @p real and @p imag parts Quaternion(T real, const Vector<T, 3>& imag) : _a(real) , _x(imag.x()) , _y(imag.y()) , _z(imag.z()) { }
void main () { try { Vector<float> v; v.Add(10); v.Add(3.4); v.Add(6.2); v.Add(9.3); v.Add(1.8); v.Add(6.7); v.Add(1.6); v.Add(3.5); v.Add(4); v.Add(8.3); //10 v.Add(7.1); v.Add(8.4); v.Add(5.3); v.Add(2.6); v.Add(3.8); v.Add(6.7); v.Add(2.5); v.Add(8.4); v.Add(2.7); v.Add(9.5); // 20 v.Add(3.9); cout << "Should print 10...3.9: " << endl; cout << v << endl; v.Add(5); v.Add(2.9); cout << "Should print 10...2.9: " << endl; cout << v << endl; v.Remove(0); cout << "Should remove 10, so should print 3.4...3.9: " << endl; cout << v << endl; // Copy constructor test CopyTest(v); Vector<float> aVector; aVector = v; cout << "Should print 3.4...3.9: " << endl; cout << aVector << endl; } catch (string error) { cout << error << endl; } system("pause"); }
bool CollisionPolygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) { if (!node) return false; Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid()) { Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform(); Vector2 gpoint = mb->get_position(); Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint); cpoint = canvas_item_editor->snap_point(cpoint); cpoint = node->get_global_transform().affine_inverse().xform(cpoint); Vector<Vector2> poly = node->get_polygon(); //first check if a point is to be added (segment split) real_t grab_threshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8); switch (mode) { case MODE_CREATE: { if (mb->get_button_index() == BUTTON_LEFT && mb->is_pressed()) { if (!wip_active) { wip.clear(); wip.push_back(cpoint); wip_active = true; edited_point_pos = cpoint; canvas_item_editor->get_viewport_control()->update(); edited_point = 1; return true; } else { if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_threshold) { //wip closed _wip_close(); return true; } else { wip.push_back(cpoint); edited_point = wip.size(); canvas_item_editor->get_viewport_control()->update(); return true; //add wip point } } } else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && wip_active) { _wip_close(); } } break; case MODE_EDIT: { if (mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { if (mb->get_control()) { if (poly.size() < 3) { undo_redo->create_action(TTR("Edit Poly")); undo_redo->add_undo_method(node, "set_polygon", poly); poly.push_back(cpoint); undo_redo->add_do_method(node, "set_polygon", poly); undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update"); undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update"); undo_redo->commit_action(); return true; } //search edges int closest_idx = -1; Vector2 closest_pos; real_t closest_dist = 1e10; for (int i = 0; i < poly.size(); i++) { Vector2 points[2] = { xform.xform(poly[i]), xform.xform(poly[(i + 1) % poly.size()]) }; Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points); if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2) continue; //not valid to reuse point real_t d = cp.distance_to(gpoint); if (d < closest_dist && d < grab_threshold) { closest_dist = d; closest_pos = cp; closest_idx = i; } } if (closest_idx >= 0) { pre_move_edit = poly; poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos)); edited_point = closest_idx + 1; edited_point_pos = xform.affine_inverse().xform(closest_pos); node->set_polygon(poly); canvas_item_editor->get_viewport_control()->update(); return true; } } else { //look for points to move int closest_idx = -1; Vector2 closest_pos; real_t closest_dist = 1e10; for (int i = 0; i < poly.size(); i++) { Vector2 cp = xform.xform(poly[i]); real_t d = cp.distance_to(gpoint); if (d < closest_dist && d < grab_threshold) { closest_dist = d; closest_pos = cp; closest_idx = i; } } if (closest_idx >= 0) { pre_move_edit = poly; edited_point = closest_idx; edited_point_pos = xform.affine_inverse().xform(closest_pos); canvas_item_editor->get_viewport_control()->update(); return true; } } } else { if (edited_point != -1) { //apply ERR_FAIL_INDEX_V(edited_point, poly.size(), false); poly[edited_point] = edited_point_pos; undo_redo->create_action(TTR("Edit Poly")); undo_redo->add_do_method(node, "set_polygon", poly); undo_redo->add_undo_method(node, "set_polygon", pre_move_edit); undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update"); undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update"); undo_redo->commit_action(); edited_point = -1; return true; } } } else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && edited_point == -1) { int closest_idx = -1; Vector2 closest_pos; real_t closest_dist = 1e10; for (int i = 0; i < poly.size(); i++) { Vector2 cp = xform.xform(poly[i]); real_t d = cp.distance_to(gpoint); if (d < closest_dist && d < grab_threshold) { closest_dist = d; closest_pos = cp; closest_idx = i; } } if (closest_idx >= 0) { undo_redo->create_action(TTR("Edit Poly (Remove Point)")); undo_redo->add_undo_method(node, "set_polygon", poly); poly.remove(closest_idx); undo_redo->add_do_method(node, "set_polygon", poly); undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update"); undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update"); undo_redo->commit_action(); return true; } } } break; } } Ref<InputEventMouseMotion> mm = p_event; if (mm.is_valid()) { if (edited_point != -1 && (wip_active || mm->get_button_mask() & BUTTON_MASK_LEFT)) { Vector2 gpoint = mm->get_position(); Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint); cpoint = canvas_item_editor->snap_point(cpoint); edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint); canvas_item_editor->get_viewport_control()->update(); } } return false; }
Vector normalize(const Vector &v) { float l = v.length(); return v / l; }
void C_Hairball::ClientThink() { // Do some AI-type stuff.. move the entity around. //C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); //m_vecAngles = SetAbsAngles( pPlayer->GetAbsAngles() ); // copy player angles. Assert( !GetMoveParent() ); // Sophisticated AI. m_flCurSpinTime += gpGlobals->frametime; if ( m_flCurSpinTime < m_flSpinDuration ) { float div = m_flCurSpinTime / m_flSpinDuration; QAngle angles = GetLocalAngles(); angles.x += m_flSpinRateX * SmoothCurve( div ); angles.y += m_flSpinRateY * SmoothCurve( div ); SetLocalAngles( angles ); } else { // Flip between stopped and starting. if ( fabs( m_flSpinRateX ) > 0.01f ) { m_flSpinRateX = m_flSpinRateY = 0; m_flSpinDuration = RandomFloat( 1, 2 ); } else { static float flXSpeed = 3; static float flYSpeed = flXSpeed * 0.1f; m_flSpinRateX = RandomFloat( -M_PI*flXSpeed, M_PI*flXSpeed ); m_flSpinRateY = RandomFloat( -M_PI*flYSpeed, M_PI*flYSpeed ); m_flSpinDuration = RandomFloat( 1, 4 ); } m_flCurSpinTime = 0; } if ( m_flSitStillTime > 0 ) { m_flSitStillTime -= gpGlobals->frametime; if ( m_flSitStillTime <= 0 ) { // Shoot out some random lines and find the longest one. m_vMoveDir.Init( 1, 0, 0 ); float flLongestFraction = 0; for ( int i=0; i < 15; i++ ) { Vector vDir( RandomFloat( -1, 1 ), RandomFloat( -1, 1 ), RandomFloat( -1, 1 ) ); VectorNormalize( vDir ); trace_t trace; UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vDir * 10000, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &trace ); if ( trace.fraction != 1.0 ) { if ( trace.fraction > flLongestFraction ) { flLongestFraction = trace.fraction; m_vMoveDir = vDir; } } } m_vMoveDir *= 650; // set speed. m_flSitStillTime = -1; // Move in this direction.. } } else { // Move in the specified direction. Vector vEnd = GetAbsOrigin() + m_vMoveDir * gpGlobals->frametime; trace_t trace; UTIL_TraceLine( GetAbsOrigin(), vEnd, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &trace ); if ( trace.fraction < 1 ) { // Ok, stop moving. m_flSitStillTime = RandomFloat( 1, 3 ); } else { SetLocalOrigin( GetLocalOrigin() + m_vMoveDir * gpGlobals->frametime ); } } // Transform the base hair positions so we can lock them down. VMatrix mTransform; mTransform.SetupMatrixOrgAngles( GetLocalOrigin(), GetLocalAngles() ); for ( int i=0; i < m_HairPositions.Count(); i++ ) { Vector3DMultiplyPosition( mTransform, m_HairPositions[i], m_TransformedHairPositions[i] ); } if ( m_bFirstThink ) { m_bFirstThink = false; for ( int i=0; i < m_HairPositions.Count(); i++ ) { for ( int j=0; j < m_nNodesPerHair; j++ ) { m_Nodes[i*m_nNodesPerHair+j].Init( m_TransformedHairPositions[i] ); } } } // Simulate the physics and apply constraints. m_Physics.Simulate( m_Nodes.Base(), m_Nodes.Count(), &m_Delegate, gpGlobals->frametime, 0.98 ); }
int main() { // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Create coarse mesh, set Dirichlet BC, enumerate basis functions. Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ, NEQ); // Enumerate basis functions, info for user. int ndof = Space::get_num_dofs(space); info("ndof: %d", ndof); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(jacobian); wf.add_vector_form(residual); // Initialize the FE problem. bool is_linear = false; DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear); // Newton's loop on coarse mesh. // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec_coarse = new double[Space::get_num_dofs(space)]; get_coeff_vector(space, coeff_vec_coarse); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix_coarse = create_matrix(matrix_solver); Vector* rhs_coarse = create_vector(matrix_solver); Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof_coarse = Space::get_num_dofs(space); // Assemble the Jacobian matrix and residual vector. dp_coarse->assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs_coarse); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_COARSE && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i)); // Solve the linear system. if(!solver_coarse->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec_coarse, space); it++; } // Cleanup. delete matrix_coarse; delete rhs_coarse; delete solver_coarse; delete [] coeff_vec_coarse; delete dp_coarse; // DOF and CPU convergence graphs. SimpleGraph graph_dof_est, graph_cpu_est; SimpleGraph graph_dof_exact, graph_cpu_exact; // Adaptivity loop: int as = 1; bool done = false; do { info("---- Adaptivity step %d:", as); // Construct globally refined reference mesh and setup reference space. Space* ref_space = construct_refined_space(space); // Initialize the FE problem. bool is_linear = false; DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Newton's loop on the fine mesh. info("Solving on fine mesh:"); // Fill vector coeff_vec using dof and coeffs arrays in elements. double *coeff_vec = new double[Space::get_num_dofs(ref_space)]; get_coeff_vector(ref_space, coeff_vec); int it = 1; while (1) { // Obtain the number of degrees of freedom. int ndof = Space::get_num_dofs(ref_space); // Assemble the Jacobian matrix and residual vector. dp->assemble(coeff_vec, matrix, rhs); // Calculate the l2-norm of residual vector. double res_l2_norm = get_l2_norm(rhs); // Info for user. info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(ref_space), res_l2_norm); // If l2 norm of the residual vector is within tolerance, then quit. // NOTE: at least one full iteration forced // here because sometimes the initial // residual on fine mesh is too small. if(res_l2_norm < NEWTON_TOL_REF && it > 1) break; // Multiply the residual vector with -1 since the matrix // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n). for(int i=0; i<ndof; i++) rhs->set(i, -rhs->get(i)); // Solve the linear system. if(!solver->solve()) error ("Matrix solver failed.\n"); // Add \deltaY^{n+1} to Y^n. for (int i = 0; i < ndof; i++) coeff_vec[i] += solver->get_solution()[i]; // If the maximum number of iteration has been reached, then quit. if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge."); // Copy coefficients from vector y to elements. set_coeff_vector(coeff_vec, ref_space); it++; } // Starting with second adaptivity step, obtain new coarse // mesh solution via projecting the fine mesh solution. if(as > 1) { info("Projecting the fine mesh solution onto the coarse mesh."); // Project the fine mesh solution (defined on space_ref) onto the coarse mesh (defined on space). OGProjection::project_global(space, ref_space, matrix_solver); } // Calculate element errors and total error estimate. info("Calculating error estimate."); double err_est_array[MAX_ELEM_NUM]; double err_est_rel = calc_err_est(NORM, space, ref_space, err_est_array) * 100; // Report results. info("ndof_coarse: %d, ndof_fine: %d, err_est_rel: %g%%", Space::get_num_dofs(space), Space::get_num_dofs(ref_space), err_est_rel); // Time measurement. cpu_time.tick(); // If exact solution available, also calculate exact error. if (EXACT_SOL_PROVIDED) { // Calculate element errors wrt. exact solution. double err_exact_rel = calc_err_exact(NORM, space, exact_sol, NEQ, A, B) * 100; // Info for user. info("Relative error (exact) = %g %%", err_exact_rel); // Add entry to DOF and CPU convergence graphs. graph_dof_exact.add_values(Space::get_num_dofs(space), err_exact_rel); graph_cpu_exact.add_values(cpu_time.accumulated(), err_exact_rel); } // Add entry to DOF and CPU convergence graphs. graph_dof_est.add_values(Space::get_num_dofs(space), err_est_rel); graph_cpu_est.add_values(cpu_time.accumulated(), err_est_rel); // Decide whether the relative error is sufficiently small. if(err_est_rel < TOL_ERR_REL) break; // Returns updated coarse and fine meshes, with the last // coarse and fine mesh solutions on them, respectively. // The coefficient vectors and numbers of degrees of freedom // on both meshes are also updated. adapt(NORM, ADAPT_TYPE, THRESHOLD, err_est_array, space, ref_space); as++; // Plot meshes, results, and errors. adapt_plotting(space, ref_space, NORM, EXACT_SOL_PROVIDED, exact_sol); // Cleanup. delete solver; delete matrix; delete rhs; delete ref_space; delete dp; delete [] coeff_vec; } while (done == false); info("Total running time: %g s", cpu_time.accumulated()); // Save convergence graphs. graph_dof_est.save("conv_dof_est.dat"); graph_cpu_est.save("conv_cpu_est.dat"); graph_dof_exact.save("conv_dof_exact.dat"); graph_cpu_exact.save("conv_cpu_exact.dat"); // Test variable. int success_test = 1; info("N_dof = %d.", Space::get_num_dofs(space)); if (Space::get_num_dofs(space) > 40) success_test = 0; if (success_test) { info("Success!"); return ERROR_SUCCESS; } else { info("Failure!"); return ERROR_FAILURE; } }
void DlgSqlExport::Run(Sql& cursor, String command, String tablename) { Title(Nvl(tablename, t_("SQL query")) + t_(" export")); object_name <<= tablename; if(!cursor.Execute(command)) { Exclamation(NFormat(t_("Error executing [* \1%s\1]: \1%s"), command, cursor.GetLastError())); return; } for(int i = 0; i < cursor.GetColumns(); i++) { const SqlColumnInfo& sci = cursor.GetColumnInfo(i); String type; switch(sci.type) { case BOOL_V: case INT_V: type = t_("integer"); break; case DOUBLE_V: type = t_("real number"); break; case STRING_V: case WSTRING_V: type = t_("string"); break; case DATE_V: type = t_("date"); break; case TIME_V: type = t_("date/time"); break; case /*ORA_BLOB_V*/-1: type = t_("BLOB"); break; case /*ORA_CLOB_V*/-2: type = t_("CLOB"); break; default: type = FormatInt(sci.type); break; } columns.Add(sci.name, sci.type, sci.width, 1); } static String cfg; LoadFromString(*this, cfg); SyncUI(); while(TopWindow::Run() == IDOK) try { String out_table = ~object_name; String delim; switch((int)~delimiters) { case DELIM_TAB: delim = "\t"; break; case DELIM_SEMICOLON: delim = ";"; break; } Vector<int> out; String colstr; String title; for(int i = 0; i < columns.GetCount(); i++) if(columns.Get(i, 3)) { out.Add(i); String cname = cursor.GetColumnInfo(i).name; colstr << (i ? ", " : "") << cname; if(i) title << delim; title << cname; } if(out.IsEmpty()) { throw Exc(t_("No columns selected!")); continue; } String rowbegin, rowend; int fmt = ~format; FileSel fsel; String ext; switch(fmt) { case FMT_TEXT: { rowend = ""; ext = ".txt"; fsel.Type(t_("Text files (*.txt)"), "*.txt"); break; } case FMT_SQL: { if(identity_insert) rowbegin << "set identity_insert " << out_table << " on "; rowbegin << "insert into " << out_table << "(" << colstr << ") values ("; rowend = ");"; ext = ".sql"; fsel.Type(t_("SQL scripts (*.sql)"), "*.sql"); break; } } fsel.AllFilesType().DefaultExt(ext.Mid(1)); if(!IsNull(recent_file)) fsel <<= ForceExt(recent_file, ext); if(!fsel.ExecuteSaveAs(t_("Save export as"))) continue; recent_file = ~fsel; FileOut fo; if(!fo.Open(recent_file)) { Exclamation(NFormat(t_("Error creating file [* \1%s\1]."), recent_file)); continue; } if(fmt == FMT_TEXT) fo.PutLine(title); Progress progress(t_("Exporting row %d")); while(cursor.Fetch()) { String script = rowbegin; for(int i = 0; i < out.GetCount(); i++) { Value v = cursor[out[i]]; switch(fmt) { case FMT_TEXT: { if(i) script.Cat(delim); if(IsString(v) && quote) { String s = v; script << '\"'; for(const char *p = s, *e = s.End(); p < e; p++) if(*p == '\"') script.Cat("\"\""); else script.Cat(*p); script << '\"'; } else script << StdFormat(v); break; } case FMT_SQL: { if(i) script.Cat(", "); script << SqlCompile(cursor.GetDialect(), SqlFormat(v)); break; } } } script << rowend; fo.PutLine(script); /* if(autocommit && --left <= 0) { fo.PutLine("commit;"); left = autocommit; } */ if(progress.StepCanceled()) { Exclamation(t_("Export aborted!")); return; } } fo.Close(); if(fo.IsError()) throw Exc(NFormat(t_("Error writing file %s."), recent_file)); break; } catch(Exc e) { ShowExc(e); } cfg = StoreAsString(*this); }
void Light::SetDirection(Vector v){ m_direction = v.d3dvector(); }
double RootMeanSquaredError::calculate_performance(const Vector<double>& parameters) const { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ check(); #endif #ifdef __OPENNN_DEBUG__ std::ostringstream buffer; const size_t size = parameters.size(); const size_t parameters_number = neural_network_pointer->count_parameters_number(); if(size != parameters_number) { buffer << "OpenNN Exception: RootMeanSquaredError class.\n" << "double calculate_performance(const Vector<double>&) const method.\n" << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ").\n"; throw std::logic_error(buffer.str()); } #endif // Neural network stuff const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer(); const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number(); const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number(); // Data set stuff const Instances& instances = data_set_pointer->get_instances(); const size_t training_instances_number = instances.count_training_instances_number(); const Vector<size_t> training_indices = instances.arrange_training_indices(); size_t training_index; const Variables& variables = data_set_pointer->get_variables(); const Vector<size_t> inputs_indices = variables.arrange_inputs_indices(); const Vector<size_t> targets_indices = variables.arrange_targets_indices(); // Root mean squared error Vector<double> inputs(inputs_number); Vector<double> outputs(outputs_number); Vector<double> targets(outputs_number); double sum_squared_error = 0.0; int i = 0; #pragma omp parallel for private(i, training_index, inputs, outputs, targets) reduction(+:sum_squared_error) for(i = 0; i < (int)training_instances_number; i++) { training_index = training_indices[i]; // Input vector inputs = data_set_pointer->get_instance(training_index, inputs_indices); // Output vector outputs = multilayer_perceptron_pointer->calculate_outputs(inputs, parameters); // Target vector targets = data_set_pointer->get_instance(training_index, targets_indices); // Sum squaresd error sum_squared_error += outputs.calculate_sum_squared_error(targets); } return(sqrt(sum_squared_error/(double)training_instances_number)); }
Vector::Vector(const Vector& v) : s{v.s}, max{v.max}, elementen{new double[v.s]} { for(int i=0; i<v.s; i++){ elementen[i]=v.get(i); } }
void TextureMapperLayer::sortByZOrder(Vector<TextureMapperLayer* >& array) { qsort(array.data(), array.size(), sizeof(TextureMapperLayer*), compareGraphicsLayersZValue); }
/** * Compute the intersection between the line segment and the capped cylinder. * * Site from is ALWAYS fluid * Site to is ALWAYS solid * * Therefore we expect exactly one intersection. Due to floating point errors, * we can't guarantee this. So, we search for intersections with some * tolerance (macro TOL) and pick the closest to fluid site (as given by the * parametic line coordinate t. We use a priority_queue to keep the hits in * order. */ Hit ComputeIntersection(CylinderData* cyl, std::vector<Iolet*>& iolets, Site& from, Site& to) { HitList hitList = HitList(); /* * The equation of the line segment is: * x(t) = a + t (b - a) t E (0, 1) */ Vector& n = cyl->Axis; double& r = cyl->Radius; Vector& c = cyl->Centre; double& h = cyl->Length; { /* * The equation determining intersection with an INFINITE cylinder of * radius r is: * [(b-a)^2 - ((b-a).n)^2] t^2 + [2 a.(b - a) - 2 (a.n)((b-a).n)] t + [a^2 - (a.n)^2 - r^2] = 0 * So first compute the coefficients and then the discriminant of the eqn */ Vector a = from.Position - c; Vector b = to.Position - c; Vector b_a = b - a; double b_aDOTn = Vector::Dot(b_a, n); double aDOTn = Vector::Dot(a, n); double A = (b_a.GetMagnitudeSquared() - b_aDOTn * b_aDOTn); double B = 2. * (Vector::Dot(a, b_a) - aDOTn * b_aDOTn); double C = a.GetMagnitudeSquared() - aDOTn * aDOTn - r * r; double discriminant = B * B - 4 * A * C; if (discriminant < 0.) { // No real solutions. } else if (discriminant == 0) { // Exactly one solution, i.e. line segment just brushes the cylinder. // This means the line must be outside the cylinder everywhere else, // so we will count this as no intersection. } else { // Two real solutions. So we have two intersections between the // infinite line and infinite cylinder. // If t outside (0,1), then the intersection isn't on the line segment // we care about. std::vector<double> ts(2); ts[0] = (-B + std::sqrt(discriminant)) / (2 * A); ts[1] = (-B - std::sqrt(discriminant)) / (2 * A); for (std::vector<double>::iterator tIt = ts.begin(); tIt != ts.end(); ++tIt) { double t = *tIt; if (t > 0. && t < 1. + TOL) { // Hit in part of line we care about. // Now check if it's on the finite cylinder. This requires that // x.n E (-h/2, h/2) double xDOTn = aDOTn + t * b_aDOTn; if (xDOTn >= -0.5 * h - TOL && xDOTn <= 0.5 * h + TOL) { // Real cylinder hit! Hit hit; hit.t = t; hit.pt = from.Position + b_a * t; hit.cellId = -1; hitList.push(hit); } } } } } /* * Now we want to look for intersections with the capping planes. */ Vector& a = from.Position; Vector& b = to.Position; Vector b_a = b - a; for (std::vector<Iolet*>::iterator iIt = iolets.begin(); iIt != iolets.end(); ++iIt) { Iolet* iolet = *iIt; /* * Plane equation is x.p = q.p (p = plane normal, q = point on plane) * Line is x = a + t(b-a) */ Vector& q = iolet->Centre; Vector& p = iolet->Normal; double t = Vector::Dot(q - a, p) / Vector::Dot(b_a, p); if (t > 0. && t < 1. + TOL) { // Intersection within the line segment. Now check within cap. Vector x = a + b_a * t; Vector x_c = x - c; double x_cDOTn = Vector::Dot(x_c, n); Vector radial = x_c - n * x_cDOTn; if (radial.GetMagnitudeSquared() < (r + TOL) * (r + TOL)) { // Within the cap Hit hit; hit.t = t; hit.pt = x; hit.cellId = iIt - iolets.begin(); hitList.push(hit); } } } // We know there SHOULD be exactly one intersection. Take the closest. if (hitList.size() == 0) throw InconsistentFluidnessError(from, to, hitList.size()); // Ensure that the hit lies on the link Hit ans = hitList.top(); if (ans.t > 1.) { ans.t = 1.; ans.pt = b; } return ans; }
bool Connection::sendOutgoingMessage(MessageID messageID, PassOwnPtr<MessageEncoder> encoder) { Vector<Attachment> attachments = encoder->releaseAttachments(); size_t numberOfPortDescriptors = 0; size_t numberOfOOLMemoryDescriptors = 0; for (size_t i = 0; i < attachments.size(); ++i) { Attachment::Type type = attachments[i].type(); if (type == Attachment::MachPortType) numberOfPortDescriptors++; else if (type == Attachment::MachOOLMemoryType) numberOfOOLMemoryDescriptors++; } size_t messageSize = machMessageSize(encoder->bufferSize(), numberOfPortDescriptors, numberOfOOLMemoryDescriptors); char buffer[inlineMessageMaxSize]; bool messageBodyIsOOL = false; if (messageSize > sizeof(buffer)) { messageBodyIsOOL = true; attachments.append(Attachment(encoder->buffer(), encoder->bufferSize(), MACH_MSG_VIRTUAL_COPY, false)); numberOfOOLMemoryDescriptors++; messageSize = machMessageSize(0, numberOfPortDescriptors, numberOfOOLMemoryDescriptors); } bool isComplex = (numberOfPortDescriptors + numberOfOOLMemoryDescriptors > 0); mach_msg_header_t* header = reinterpret_cast<mach_msg_header_t*>(&buffer); header->msgh_bits = isComplex ? MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND | MACH_MSGH_BITS_COMPLEX, 0) : MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0); header->msgh_size = messageSize; header->msgh_remote_port = m_sendPort; header->msgh_local_port = MACH_PORT_NULL; header->msgh_id = messageID.toInt(); if (messageBodyIsOOL) header->msgh_id |= MessageBodyIsOOL; uint8_t* messageData; if (isComplex) { mach_msg_body_t* body = reinterpret_cast<mach_msg_body_t*>(header + 1); body->msgh_descriptor_count = numberOfPortDescriptors + numberOfOOLMemoryDescriptors; uint8_t* descriptorData = reinterpret_cast<uint8_t*>(body + 1); for (size_t i = 0; i < attachments.size(); ++i) { Attachment attachment = attachments[i]; mach_msg_descriptor_t* descriptor = reinterpret_cast<mach_msg_descriptor_t*>(descriptorData); switch (attachment.type()) { case Attachment::MachPortType: descriptor->port.name = attachment.port(); descriptor->port.disposition = attachment.disposition(); descriptor->port.type = MACH_MSG_PORT_DESCRIPTOR; descriptorData += sizeof(mach_msg_port_descriptor_t); break; case Attachment::MachOOLMemoryType: descriptor->out_of_line.address = attachment.address(); descriptor->out_of_line.size = attachment.size(); descriptor->out_of_line.copy = attachment.copyOptions(); descriptor->out_of_line.deallocate = attachment.deallocate(); descriptor->out_of_line.type = MACH_MSG_OOL_DESCRIPTOR; descriptorData += sizeof(mach_msg_ool_descriptor_t); break; default: ASSERT_NOT_REACHED(); } } messageData = descriptorData; } else messageData = (uint8_t*)(header + 1); // Copy the data if it is not being sent out-of-line. if (!messageBodyIsOOL) memcpy(messageData, encoder->buffer(), encoder->bufferSize()); ASSERT(m_sendPort); // Send the message. kern_return_t kr = mach_msg(header, MACH_SEND_MSG, messageSize, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kr != KERN_SUCCESS) { // FIXME: What should we do here? } return true; }
//------------------------------------------------------------------------------ // Purpose : Update the direction and position of my spotlight // Input : // Output : //------------------------------------------------------------------------------ void CPointSpotlight::SpotlightUpdate(void) { // --------------------------------------------------- // If I don't have a spotlight attempt to create one // --------------------------------------------------- if ( !m_hSpotlight ) { if ( m_bSpotlightOn ) { // Make the spotlight SpotlightCreate(); } else { return; } } else if ( !m_bSpotlightOn ) { SpotlightDestroy(); return; } if ( !m_hSpotlightTarget ) { DevWarning( "**Attempting to update point_spotlight but target ent is NULL\n" ); SpotlightDestroy(); SpotlightCreate(); if ( !m_hSpotlightTarget ) return; } m_vSpotlightCurrentPos = SpotlightCurrentPos(); // Update spotlight target velocity Vector vTargetDir; VectorSubtract( m_vSpotlightCurrentPos, m_hSpotlightTarget->GetAbsOrigin(), vTargetDir ); float vTargetDist = vTargetDir.Length(); // If we haven't moved at all, don't recompute if ( vTargetDist < 1 ) { m_hSpotlightTarget->SetAbsVelocity( vec3_origin ); return; } Vector vecNewVelocity = vTargetDir; VectorNormalize(vecNewVelocity); vecNewVelocity *= (10 * vTargetDist); // If a large move is requested, just jump to final spot as we probably hit a discontinuity if (vecNewVelocity.Length() > 200) { VectorNormalize(vecNewVelocity); vecNewVelocity *= 200; VectorNormalize(vTargetDir); m_hSpotlightTarget->SetAbsOrigin( m_vSpotlightCurrentPos ); } m_hSpotlightTarget->SetAbsVelocity( vecNewVelocity ); m_hSpotlightTarget->m_vSpotlightOrg = GetAbsOrigin(); // Avoid sudden change in where beam fades out when cross disconinuities VectorSubtract( m_hSpotlightTarget->GetAbsOrigin(), m_hSpotlightTarget->m_vSpotlightOrg, m_hSpotlightTarget->m_vSpotlightDir ); float flBeamLength = VectorNormalize( m_hSpotlightTarget->m_vSpotlightDir ); m_flSpotlightCurLength = (0.60*m_flSpotlightCurLength) + (0.4*flBeamLength); ComputeRenderInfo(); //NDebugOverlay::Cross3D(GetAbsOrigin(),Vector(-5,-5,-5),Vector(5,5,5),0,255,0,true,0.1); //NDebugOverlay::Cross3D(m_vSpotlightCurrentPos,Vector(-5,-5,-5),Vector(5,5,5),0,255,0,true,0.1); //NDebugOverlay::Cross3D(m_vSpotlightTargetPos,Vector(-5,-5,-5),Vector(5,5,5),255,0,0,true,0.1); }
static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* l, const LayoutRect& paintRect, int indent, RenderAsTextBehavior behavior) { // FIXME: Apply overflow to the root layer to not break every test. Complete hack. Sigh. LayoutRect paintDirtyRect(paintRect); if (rootLayer == l) { paintDirtyRect.setWidth(max<LayoutUnit>(paintDirtyRect.width(), rootLayer->renderBox()->layoutOverflowRect().maxX())); paintDirtyRect.setHeight(max<LayoutUnit>(paintDirtyRect.height(), rootLayer->renderBox()->layoutOverflowRect().maxY())); l->setSize(l->size().expandedTo(pixelSnappedIntSize(l->renderBox()->maxLayoutOverflow(), LayoutPoint(0, 0)))); } // Calculate the clip rects we should use. LayoutRect layerBounds; ClipRect damageRect, clipRectToApply, outlineRect; l->calculateRects(rootLayer, 0, TemporaryClipRects, paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect); // Ensure our lists are up-to-date. l->updateLayerListsIfNeeded(); bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : l->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer); Vector<RenderLayer*>* negList = l->negZOrderList(); bool paintsBackgroundSeparately = negList && negList->size() > 0; if (shouldPaint && paintsBackgroundSeparately) write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior); if (negList) { int currIndent = indent; if (behavior & RenderAsTextShowLayerNesting) { writeIndent(ts, indent); ts << " negative z-order list(" << negList->size() << ")\n"; ++currIndent; } for (unsigned i = 0; i != negList->size(); ++i) writeLayers(ts, rootLayer, negList->at(i), paintDirtyRect, currIndent, behavior); } if (shouldPaint) write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior); if (Vector<RenderLayer*>* normalFlowList = l->normalFlowList()) { int currIndent = indent; if (behavior & RenderAsTextShowLayerNesting) { writeIndent(ts, indent); ts << " normal flow list(" << normalFlowList->size() << ")\n"; ++currIndent; } for (unsigned i = 0; i != normalFlowList->size(); ++i) writeLayers(ts, rootLayer, normalFlowList->at(i), paintDirtyRect, currIndent, behavior); } if (Vector<RenderLayer*>* posList = l->posZOrderList()) { int currIndent = indent; if (behavior & RenderAsTextShowLayerNesting) { writeIndent(ts, indent); ts << " positive z-order list(" << posList->size() << ")\n"; ++currIndent; } for (unsigned i = 0; i != posList->size(); ++i) writeLayers(ts, rootLayer, posList->at(i), paintDirtyRect, currIndent, behavior); } // Altough the RenderFlowThread requires a layer, it is not collected by its parent, // so we have to treat it as a special case. if (l->renderer()->isRenderView()) { RenderView* renderView = toRenderView(l->renderer()); writeRenderNamedFlowThreads(ts, renderView, rootLayer, paintDirtyRect, indent, behavior); } }
int main(int argc, char** argv) { Color color; float zpf = 0.5; //primitive is double, causes problems float zpt = 0.25; float zps = 0.75; Camera cam = Camera(); raytracer = Raytracer(cam.eye, 16, Color(0,0,0), Color(0.1,0.1,0.1)); UL = Vector(-1, 1, 1); UR = Vector( 1, 1, 1); LR = Vector( 1, -1, 1); LL = Vector(-1, -1, 1); Image screen = Image(width, height); //Triangle triangle(Vector(-9,-5,10),Vector(-3,-5,13),Vector(-6,5,10), Color(1,0.5,0.25)); //raytracer.registerShape(triangle); //Sphere sphere = Sphere(Vector(0, 0, 10), 3, Color(0.5,0.5,0.5)); //raytracer.registerShape(sphere); //Sphere sphere2 = Sphere(Vector(3, 0, 6), 1, Color(0.25,0.5,1)); //raytracer.registerShape(sphere2); Triangle triangle = Triangle (Vector (-5, -5, 10), Vector(5, -5, 10), Vector(0, 5, 10)); raytracer.registerShape(triangle); Light light = Light(0,0,0,1,0,1); raytracer.registerLight(light); for(float k = 0; k < height; k++) { for(float i = 0; i < width; i++) { float u = (i + zpf) / width; float v = (k + zpf) / height; Vector dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); Ray ray = Ray(cam.eye, dir); PoI poi = PoI(); bool gotHit = intersect_search(ray, triangles, 1, &poi); //PoI intersect = PoI(Vector(0,0,0), Vector(0,0,0)); //bool gotHit = triangle.hit(ray, &intersect); //gotHit = gotHit || sphere.hit(ray, &intersect); Color color1 = raytracer.trace(ray, 1); u = (i + 2*zpt) / width; v = (k + zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color2 = raytracer.trace(ray, 1); u = (i + 3*zpt) / width; v = (k + zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color3 = raytracer.trace(ray, 1); u = (i + zpt) / width; v = (k + 2*zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color4 = raytracer.trace(ray, 1); u = (i + zpt) / width; v = (k + 3*zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color5 = raytracer.trace(ray, 1); u = (i + 2*zpt) / width; v = (k + 2*zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color6 = raytracer.trace(ray, 1); u = (i + 2*zpt) / width; v = (k + 3*zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color7 = raytracer.trace(ray, 1); u = (i + 3*zpt) / width; v = (k + 2*zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color8 = raytracer.trace(ray, 1); u = (i + 3*zpt) / width; v = (k + 3*zpt) / height; dir = ((UR.Vsca(v)).Vadd(UL.Vsca(1-v)).Vsca(u)).Vadd((LR.Vsca(v)).Vadd(LL.Vsca(1-v)).Vsca(1-u)).Vsub(cam.eye).Vnor(); ray = Ray(cam.eye, dir); Color color9 = raytracer.trace(ray, 1); /*if (gotHit) { color = poi.getColor(); //Ray shadow_ray. origin = poi.coliision, dir -> to light <<<<<<<<---- thingies for shadows //bool isShadowed = intersect_search(shadow_ray, tra...) //if(isShadowed) // color = 0; //else //color = poi.shade(light); } else { color = Color(0, 0, 0); }*/ //color = VtoC((CtoV(color1).Vadd(CtoV(color2)).Vadd(CtoV(color3)).Vadd(CtoV(color4)).Vadd(CtoV(color5)).Vadd(CtoV(color6)).Vadd(CtoV(color7)).Vadd(CtoV(color8)).Vadd(CtoV(color9))).Vdiv(9)); if(!screen.setPixel(k, i, color1)) { printf("There was a problem!\n"); } } } screen.flush(); return 0; }
double LocaleWin::parseDate(const Vector<DateFormatToken>& tokens, int baseYear, const String& input) { ensureShortMonthLabels(); ensureMonthLabels(); const double NaN = numeric_limits<double>::quiet_NaN(); unsigned inputIndex = 0; int day = -1, month = -1, year = -1; for (unsigned i = 0; i < tokens.size(); ++i) { switch (tokens[i].type) { case DateFormatToken::Literal: { String data = tokens[i].data; unsigned literalLength = data.length(); if (input.substring(inputIndex, literalLength) == data) inputIndex += literalLength; // Go ahead even if the input doesn't have this string. break; } case DateFormatToken::Day1: case DateFormatToken::Day2: day = parseNumber(input, inputIndex); if (day < 1 || day > 31) return NaN; break; case DateFormatToken::Month1: case DateFormatToken::Month2: case DateFormatToken::Month3: case DateFormatToken::Month4: month = parseNumberOrMonth(input, inputIndex); if (month < 0 || month > 11) return NaN; break; case DateFormatToken::Year1: { unsigned oldIndex = inputIndex; year = parseNumber(input, inputIndex); if (year <= 0) return NaN; if (inputIndex - oldIndex == 1) { int shortYear = baseYear % 10; int decade = baseYear - shortYear; if (shortYear >= 5) year += shortYear - 4 <= year ? decade : decade + 10; else year += shortYear + 5 >= year ? decade : decade - 10; } break; } case DateFormatToken::Year2: { unsigned oldIndex = inputIndex; year = parseNumber(input, inputIndex); if (year <= 0) return NaN; if (inputIndex - oldIndex == 2) { int shortYear = baseYear % 100; int century = baseYear - shortYear; if (shortYear >= 50) year += shortYear - 49 <= year ? century : century + 100; else year += shortYear + 50 >= year ? century : century - 100; } break; } case DateFormatToken::Year4: year = parseNumber(input, inputIndex); if (year <= 0) return NaN; break; } } if (year <= 0 || month < 0 || day <= 0) return NaN; return dateToDaysFrom1970(year, month, day) * msPerDay; }
int main(int argc, char *argv[]) { Network yarp; Property params; Robot * robot; PositionImpedanceThd* controllerLeftArm; PositionImpedanceThd* controllerRightArm; JointImpedance *jointImpedance; //Vector jointImpedance; int joint,nJoints; // Create context params.fromCommand(argc, argv); if (!params.check("robot")) { fprintf(stderr, "Please specify the name of the robot\n"); fprintf(stderr, " --robot name (e.g. icub, icubSim)\n"); return -1; } //Initialize the Robot robot = new Robot(0); robot->init(params.find("robot").asString().c_str()); // Stiffness vector nJoints = robot->get_dof(LEFT_ARM); jointImpedanceVec.resize(nJoints); // Default stiffness for (joint = 0; joint < nJoints; ++joint) { jointImpedanceVec[joint] = 0; } //Controller threads controllerLeftArm = new PositionImpedanceThd( robot->get_driver(LEFT_ARM), (double) REFSPEED, (double) REFACC, jointImpedanceVec, (double) PCONTROLLER); controllerRightArm = new PositionImpedanceThd( robot->get_driver(RIGHT_ARM), (double) REFSPEED, (double) REFACC, jointImpedanceVec, (double) PCONTROLLER); jointImpedance = new JointImpedance(robot->get_driver(LEFT_ARM), robot->get_driver(RIGHT_ARM), PUPDATE, REST); // Starting the controllers threads if (!controllerLeftArm->start()) { delete controllerLeftArm; delete controllerRightArm; delete jointImpedance; return -1; } if (!controllerRightArm->start()) { delete controllerLeftArm; delete controllerRightArm; delete jointImpedance; return -1; } sleep(1); //SetPoints Vector bool doneLeft, doneRight; jointsLeft.resize(nJoints); jointsRight.resize(nJoints); /* * Phase 1 - Initial position * * Stiff movement to the initial arm position. */ printf("\n+++ Phase 1.\n"); firstPhase(); controllerLeftArm->enableImpedance(jointImpedanceVec); controllerLeftArm->setJoints(jointsLeft); controllerRightArm->setJoints(jointsRight); sleep(3); printf("+++ Finished phase 1.\n"); /* * Phase 2 - Two handed grasping * * Compliant movement to grasp an object between the arms. */ printf("\n+++ Phase 2.\n"); secondPhase(); controllerLeftArm->enableImpedance(jointImpedanceVec); controllerLeftArm->setJoints(jointsLeft); controllerRightArm->setJoints(jointsRight); sleep(3); printf("+++ Finished phase 2.\n"); int go; cout << "Press any key for the variable impedance control phase..." << endl; cin >> go; /* * Phase 3 - Two-Handed Object Tracking * * Following the object */ printf("\n+++ Phase 3.\n"); if (!jointImpedance->start()){ delete controllerLeftArm; delete controllerRightArm; delete jointImpedance; return -1; } while(getchar() != 'a'){} jointImpedance->stop(); /* * Tear down * * Releasing the object, deconstructing */ // Back to initial arm position printf("\n+++ Phase 4.\n"); fourthPhase(); controllerLeftArm->setJoints(jointsLeft); controllerRightArm->setJoints(jointsRight); sleep(3); printf("+++ Finished phase 4.\n"); printf("\n+++ Released the object, Demo finished.\n"); controllerLeftArm->stop(); controllerRightArm->stop(); delete robot; delete controllerLeftArm; delete controllerRightArm; delete jointImpedance; return 0; }
bool convertWOFFToSfnt(SharedBuffer* woff, Vector<char>& sfnt) { ASSERT_ARG(sfnt, sfnt.isEmpty()); size_t offset = 0; // Read the WOFF header. uint32_t signature; if (!readUInt32(woff, offset, signature) || signature != woffSignature) { ASSERT_NOT_REACHED(); return false; } uint32_t flavor; if (!readUInt32(woff, offset, flavor)) return false; uint32_t length; if (!readUInt32(woff, offset, length) || length != woff->size()) return false; uint16_t numTables; if (!readUInt16(woff, offset, numTables)) return false; if (!numTables || numTables > 0x0fff) return false; uint16_t reserved; if (!readUInt16(woff, offset, reserved) || reserved) return false; uint32_t totalSfntSize; if (!readUInt32(woff, offset, totalSfntSize)) return false; if (woff->size() - offset < sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t)) return false; offset += sizeof(uint16_t); // majorVersion offset += sizeof(uint16_t); // minorVersion offset += sizeof(uint32_t); // metaOffset offset += sizeof(uint32_t); // metaLength offset += sizeof(uint32_t); // metaOrigLength offset += sizeof(uint32_t); // privOffset offset += sizeof(uint32_t); // privLength // Check if the WOFF can supply as many tables as it claims it has. if (woff->size() - offset < numTables * 5 * sizeof(uint32_t)) return false; // Write the sfnt offset subtable. uint16_t entrySelector = 0; uint16_t searchRange = 1; while (searchRange < numTables >> 1) { entrySelector++; searchRange <<= 1; } searchRange <<= 4; uint16_t rangeShift = (numTables << 4) - searchRange; if (!writeUInt32(sfnt, flavor) || !writeUInt16(sfnt, numTables) || !writeUInt16(sfnt, searchRange) || !writeUInt16(sfnt, entrySelector) || !writeUInt16(sfnt, rangeShift)) return false; if (sfnt.size() > totalSfntSize) return false; if (totalSfntSize - sfnt.size() < numTables * 4 * sizeof(uint32_t)) return false; size_t sfntTableDirectoryCursor = sfnt.size(); sfnt.grow(sfnt.size() + numTables * 4 * sizeof(uint32_t)); // Process tables. for (uint16_t i = 0; i < numTables; ++i) { // Read a WOFF table directory entry. uint32_t tableTag; if (!readUInt32(woff, offset, tableTag)) return false; uint32_t tableOffset; if (!readUInt32(woff, offset, tableOffset)) return false; uint32_t tableCompLength; if (!readUInt32(woff, offset, tableCompLength)) return false; if (tableOffset > woff->size() || tableCompLength > woff->size() - tableOffset) return false; uint32_t tableOrigLength; if (!readUInt32(woff, offset, tableOrigLength) || tableCompLength > tableOrigLength) return false; if (tableOrigLength > totalSfntSize || sfnt.size() > totalSfntSize - tableOrigLength) return false; uint32_t tableOrigChecksum; if (!readUInt32(woff, offset, tableOrigChecksum)) return false; // Write an sfnt table directory entry. uint32_t* sfntTableDirectoryPtr = reinterpret_cast<uint32_t*>(sfnt.data() + sfntTableDirectoryCursor); *sfntTableDirectoryPtr++ = htonl(tableTag); *sfntTableDirectoryPtr++ = htonl(tableOrigChecksum); *sfntTableDirectoryPtr++ = htonl(sfnt.size()); *sfntTableDirectoryPtr++ = htonl(tableOrigLength); sfntTableDirectoryCursor += 4 * sizeof(uint32_t); if (tableCompLength == tableOrigLength) { // The table is not compressed. if (!sfnt.tryAppend(woff->data() + tableOffset, tableCompLength)) return false; } else { uLongf destLen = tableOrigLength; if (!sfnt.tryReserveCapacity(sfnt.size() + tableOrigLength)) return false; Bytef* dest = reinterpret_cast<Bytef*>(sfnt.end()); sfnt.grow(sfnt.size() + tableOrigLength); if (uncompress(dest, &destLen, reinterpret_cast<const Bytef*>(woff->data() + tableOffset), tableCompLength) != Z_OK) return false; if (destLen != tableOrigLength) return false; } // Pad to a multiple of 4 bytes. while (sfnt.size() % 4) sfnt.append(0); } return sfnt.size() == totalSfntSize; }
int TclModelBuilder_addRJWatsonEqsBearing(ClientData clientData, Tcl_Interp *interp, int argc, TCL_Char **argv, Domain *theTclDomain, TclModelBuilder *theTclBuilder, int eleArgStart) { // ensure the destructor has not been called if (theTclBuilder == 0) { opserr << "WARNING builder has been destroyed - RJWatsonEqsBearing\n"; return TCL_ERROR; } Element *theElement = 0; int ndm = theTclBuilder->getNDM(); int ndf = theTclBuilder->getNDF(); int tag; if (ndm == 2) { // check plane frame problem has 3 dof per node if (ndf != 3) { opserr << "WARNING invalid ndf: " << ndf; opserr << ", for plane problem need 3 - RJWatsonEqsBearing\n"; return TCL_ERROR; } // check the number of arguments is correct if ((argc-eleArgStart) < 13) { opserr << "WARNING insufficient arguments\n"; printCommand(argc, argv); opserr << "Want: RJWatsonEqsBearing eleTag iNode jNode frnMdlTag kInit k2 k3 mu -P matTag -Mz matTag <-orient x1 x2 x3 y1 y2 y3> <-shearDist sDratio> <-doRayleigh> <-mass m> <-iter maxIter tol>\n"; return TCL_ERROR; } // get the id and end nodes int iNode, jNode, frnMdlTag, matTag, argi, i, j; int recvMat = 0; double kInit, k2; double k3 = 0.0; double mu = 2.0; double shearDistI = 1.0; int doRayleigh = 0; double mass = 0.0; int maxIter = 25; double tol = 1E-12; double kFactUplift = 1E-6; if (Tcl_GetInt(interp, argv[1+eleArgStart], &tag) != TCL_OK) { opserr << "WARNING invalid RJWatsonEqsBearing eleTag\n"; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[2+eleArgStart], &iNode) != TCL_OK) { opserr << "WARNING invalid iNode\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[3+eleArgStart], &jNode) != TCL_OK) { opserr << "WARNING invalid jNode\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[4+eleArgStart], &frnMdlTag) != TCL_OK) { opserr << "WARNING invalid frnMdlTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } FrictionModel *theFrnMdl = OPS_getFrictionModel(frnMdlTag); if (theFrnMdl == 0) { opserr << "WARNING friction model not found\n"; opserr << "frictionModel: " << frnMdlTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[5+eleArgStart], &kInit) != TCL_OK) { opserr << "WARNING invalid kInit\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[6+eleArgStart], &k2) != TCL_OK) { opserr << "WARNING invalid k2\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[7+eleArgStart], &k3) != TCL_OK) { opserr << "WARNING invalid k3\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[8+eleArgStart], &mu) != TCL_OK) { opserr << "WARNING invalid mu\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } UniaxialMaterial *theMaterials[2]; for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-P") == 0) { theMaterials[0] = 0; if (Tcl_GetInt(interp, argv[i+1], &matTag) != TCL_OK) { opserr << "WARNING invalid matTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } theMaterials[0] = OPS_getUniaxialMaterial(matTag); if (theMaterials[0] == 0) { opserr << "WARNING material model not found\n"; opserr << "uniaxialMaterial: " << matTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } recvMat++; } } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-Mz") == 0) { if (Tcl_GetInt(interp, argv[i+1], &matTag) != TCL_OK) { opserr << "WARNING invalid matTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } theMaterials[1] = OPS_getUniaxialMaterial(matTag); if (theMaterials[1] == 0) { opserr << "WARNING material model not found\n"; opserr << "uniaxialMaterial: " << matTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } recvMat++; } } if (recvMat != 2) { opserr << "WARNING wrong number of materials\n"; opserr << "got " << recvMat << " materials, but want 2 materials\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } // check for optional arguments Vector x = 0; Vector y = 0; for (i = 9+eleArgStart; i < argc; i++) { if (strcmp(argv[i],"-orient") == 0) { j = i+1; int numOrient = 0; while (j < argc && strcmp(argv[j],"-shearDist") != 0 && strcmp(argv[j],"-doRayleigh") != 0 && strcmp(argv[j],"-mass") != 0 && strcmp(argv[j],"-iter") != 0 && strcmp(argv[j],"-kFactUplift") != 0) { numOrient++; j++; } if (numOrient == 6) { argi = i+1; x.resize(3); y.resize(3); double value; // read the x values for (j=0; j<3; j++) { if (Tcl_GetDouble(interp, argv[argi], &value) != TCL_OK) { opserr << "WARNING invalid -orient value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } else { argi++; x(j) = value; } } // read the y values for (j=0; j<3; j++) { if (Tcl_GetDouble(interp, argv[argi], &value) != TCL_OK) { opserr << "WARNING invalid -orient value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } else { argi++; y(j) = value; } } } else { opserr << "WARNING insufficient arguments after -orient flag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (int i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-shearDist") == 0) { if (Tcl_GetDouble(interp, argv[i+1], &shearDistI) != TCL_OK) { opserr << "WARNING invalid -shearDist value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (int i = 9+eleArgStart; i < argc; i++) { if (strcmp(argv[i], "-doRayleigh") == 0) doRayleigh = 1; } for (int i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-mass") == 0) { if (Tcl_GetDouble(interp, argv[i+1], &mass) != TCL_OK) { opserr << "WARNING invalid -mass value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (int i = 9+eleArgStart; i < argc; i++) { if (i+2 < argc && strcmp(argv[i], "-iter") == 0) { if (Tcl_GetInt(interp, argv[i+1], &maxIter) != TCL_OK) { opserr << "WARNING invalid maxIter\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i+2], &tol) != TCL_OK) { opserr << "WARNING invalid tol\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (int i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-kFactUplift") == 0) { if (Tcl_GetDouble(interp, argv[i+1], &kFactUplift) != TCL_OK) { opserr << "WARNING invalid kFactUplift\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } // now create the RJWatsonEqsBearing theElement = new RJWatsonEQS2d(tag, iNode, jNode, *theFrnMdl, kInit, k2, theMaterials, y, x, k3, mu, shearDistI, doRayleigh, mass, maxIter, tol, kFactUplift); if (theElement == 0) { opserr << "WARNING ran out of memory creating element\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } // then add the RJWatsonEqsBearing to the domain if (theTclDomain->addElement(theElement) == false) { opserr << "WARNING could not add element to the domain\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; delete theElement; return TCL_ERROR; } } else if (ndm == 3) { // check space frame problem has 6 dof per node if (ndf != 6) { opserr << "WARNING invalid ndf: " << ndf; opserr << ", for space problem need 6 - RJWatsonEqsBearing \n"; return TCL_ERROR; } // check the number of arguments is correct if ((argc-eleArgStart) < 17) { opserr << "WARNING insufficient arguments\n"; printCommand(argc, argv); opserr << "Want: RJWatsonEqsBearing eleTag iNode jNode frnMdlTag kInit k2 k3 mu -P matTag -T matTag -My matTag -Mz matTag <-orient <x1 x2 x3> y1 y2 y3> <-shearDist sDratio> <-doRayleigh> <-mass m> <-iter maxIter tol>\n"; return TCL_ERROR; } // get the id and end nodes int iNode, jNode, frnMdlTag, matTag, argi, i, j; int recvMat = 0; double kInit, k2; double k3 = 0.0; double mu = 2.0; double shearDistI = 1.0; int doRayleigh = 0; double mass = 0.0; int maxIter = 25; double tol = 1E-12; double kFactUplift = 1E-6; if (Tcl_GetInt(interp, argv[1+eleArgStart], &tag) != TCL_OK) { opserr << "WARNING invalid RJWatsonEqsBearing eleTag\n"; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[2+eleArgStart], &iNode) != TCL_OK) { opserr << "WARNING invalid iNode\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[3+eleArgStart], &jNode) != TCL_OK) { opserr << "WARNING invalid jNode\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetInt(interp, argv[4+eleArgStart], &frnMdlTag) != TCL_OK) { opserr << "WARNING invalid frnMdlTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } FrictionModel *theFrnMdl = OPS_getFrictionModel(frnMdlTag); if (theFrnMdl == 0) { opserr << "WARNING friction model not found\n"; opserr << "frictionModel: " << frnMdlTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[5+eleArgStart], &kInit) != TCL_OK) { opserr << "WARNING invalid kInit\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[6+eleArgStart], &k2) != TCL_OK) { opserr << "WARNING invalid k2\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[7+eleArgStart], &k3) != TCL_OK) { opserr << "WARNING invalid k3\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[8+eleArgStart], &mu) != TCL_OK) { opserr << "WARNING invalid mu\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } UniaxialMaterial *theMaterials[4]; for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-P") == 0) { if (Tcl_GetInt(interp, argv[i+1], &matTag) != TCL_OK) { opserr << "WARNING invalid axial matTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } theMaterials[0] = OPS_getUniaxialMaterial(matTag); if (theMaterials[0] == 0) { opserr << "WARNING material model not found\n"; opserr << "uniaxialMaterial: " << matTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } recvMat++; } } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-T") == 0) { if (Tcl_GetInt(interp, argv[i+1], &matTag) != TCL_OK) { opserr << "WARNING invalid torsional matTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } theMaterials[1] = OPS_getUniaxialMaterial(matTag); if (theMaterials[1] == 0) { opserr << "WARNING material model not found\n"; opserr << "uniaxialMaterial: " << matTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } recvMat++; } } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-My") == 0) { if (Tcl_GetInt(interp, argv[i+1], &matTag) != TCL_OK) { opserr << "WARNING invalid moment y matTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } theMaterials[2] = OPS_getUniaxialMaterial(matTag); if (theMaterials[2] == 0) { opserr << "WARNING material model not found\n"; opserr << "uniaxialMaterial: " << matTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } recvMat++; } } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-Mz") == 0) { if (Tcl_GetInt(interp, argv[i+1], &matTag) != TCL_OK) { opserr << "WARNING invalid moment z matTag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } theMaterials[3] = OPS_getUniaxialMaterial(matTag); if (theMaterials[3] == 0) { opserr << "WARNING material model not found\n"; opserr << "uniaxialMaterial: " << matTag << endln; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } recvMat++; } } if (recvMat != 4) { opserr << "WARNING wrong number of materials\n"; opserr << "got " << recvMat << " materials, but want 4 materials\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } // check for optional arguments Vector x(0); Vector y(3); y(0) = 0.0; y(1) = 1.0; y(2) = 0.0; for (i = 9+eleArgStart; i < argc; i++) { if (strcmp(argv[i],"-orient") == 0) { j = i+1; int numOrient = 0; while (j < argc && strcmp(argv[j],"-shearDist") != 0 && strcmp(argv[j],"-doRayleigh") != 0 && strcmp(argv[j],"-mass") != 0 && strcmp(argv[j],"-iter") != 0 && strcmp(argv[j],"-kFactUplift") != 0) { numOrient++; j++; } if (numOrient == 3) { argi = i+1; double value; // read the y values for (j=0; j<3; j++) { if (Tcl_GetDouble(interp, argv[argi], &value) != TCL_OK) { opserr << "WARNING invalid -orient value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } else { argi++; y(j) = value; } } } else if (numOrient == 6) { argi = i+1; x.resize(3); double value; // read the x values for (j=0; j<3; j++) { if (Tcl_GetDouble(interp, argv[argi], &value) != TCL_OK) { opserr << "WARNING invalid -orient value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } else { argi++; x(j) = value; } } // read the y values for (j=0; j<3; j++) { if (Tcl_GetDouble(interp, argv[argi], &value) != TCL_OK) { opserr << "WARNING invalid -orient value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } else { argi++; y(j) = value; } } } else { opserr << "WARNING insufficient arguments after -orient flag\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-shearDist") == 0) { if (Tcl_GetDouble(interp, argv[i+1], &shearDistI) != TCL_OK) { opserr << "WARNING invalid -shearDist value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-doRayleigh") == 0) doRayleigh = 1; } for (i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-mass") == 0) { if (Tcl_GetDouble(interp, argv[i+1], &mass) != TCL_OK) { opserr << "WARNING invalid -mass value\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (int i = 9+eleArgStart; i < argc; i++) { if (i+2 < argc && strcmp(argv[i], "-iter") == 0) { if (Tcl_GetInt(interp, argv[i+1], &maxIter) != TCL_OK) { opserr << "WARNING invalid maxIter\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } if (Tcl_GetDouble(interp, argv[i+2], &tol) != TCL_OK) { opserr << "WARNING invalid tol\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } } } for (int i = 9+eleArgStart; i < argc; i++) { if (i+1 < argc && strcmp(argv[i], "-kFactUplift") == 0) { if (Tcl_GetDouble(interp, argv[i+1], &kFactUplift) != TCL_OK) { opserr << "WARNING invalid kFactUplift\n"; opserr << "singleFPBearing element: " << tag << endln; return TCL_ERROR; } } } // now create the RJWatsonEqsBearing theElement = new RJWatsonEQS3d(tag, iNode, jNode, *theFrnMdl, kInit, k2, theMaterials, y, x, k3, mu, shearDistI, doRayleigh, mass, maxIter, tol, kFactUplift); if (theElement == 0) { opserr << "WARNING ran out of memory creating element\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; return TCL_ERROR; } // then add the RJWatsonEqsBearing to the domain if (theTclDomain->addElement(theElement) == false) { opserr << "WARNING could not add element to the domain\n"; opserr << "RJWatsonEqsBearing element: " << tag << endln; delete theElement; return TCL_ERROR; } } else { opserr << "WARNING RJWatsonEqsBearing command only works when ndm is 2 or 3, ndm: "; opserr << ndm << endln; return TCL_ERROR; } // if get here we have sucessfully created the RJWatsonEqsBearing and added it to the domain return TCL_OK; }
JSBool js_StartPerf() { const char *outfile = "mozperf.data"; if (perfPid != 0) { UnsafeError("js_StartPerf: called while perf was already running!\n"); return false; } // Bail if MOZ_PROFILE_WITH_PERF is empty or undefined. if (!getenv("MOZ_PROFILE_WITH_PERF") || !strlen(getenv("MOZ_PROFILE_WITH_PERF"))) { return true; } /* * Delete mozperf.data the first time through -- we're going to append to it * later on, so we want it to be clean when we start out. */ if (!perfInitialized) { perfInitialized = true; unlink(outfile); char cwd[4096]; printf("Writing perf profiling data to %s/%s\n", getcwd(cwd, sizeof(cwd)), outfile); } pid_t mainPid = getpid(); pid_t childPid = fork(); if (childPid == 0) { /* perf record --append --pid $mainPID --output=$outfile $MOZ_PROFILE_PERF_FLAGS */ char mainPidStr[16]; snprintf(mainPidStr, sizeof(mainPidStr), "%d", mainPid); const char *defaultArgs[] = {"perf", "record", "--append", "--pid", mainPidStr, "--output", outfile}; Vector<const char*, 0, SystemAllocPolicy> args; args.append(defaultArgs, ArrayLength(defaultArgs)); const char *flags = getenv("MOZ_PROFILE_PERF_FLAGS"); if (!flags) { flags = "--call-graph"; } // Split |flags| on spaces. (Don't bother to free it -- we're going to // exec anyway.) char *toksave; char *tok = strtok_r(strdup(flags), " ", &toksave); while (tok) { args.append(tok); tok = strtok_r(NULL, " ", &toksave); } args.append((char*) NULL); execvp("perf", const_cast<char**>(args.begin())); /* Reached only if execlp fails. */ fprintf(stderr, "Unable to start perf.\n"); exit(1); } else if (childPid > 0) { perfPid = childPid; /* Give perf a chance to warm up. */ usleep(500 * 1000); return true; } else { UnsafeError("js_StartPerf: fork() failed\n"); return false; } }
Matrix& Matrix::SetLookAtFrom(const Vector& vecAt, const Vector& vecFrom, const Vector& vecUp) { Vector vecZAxis = (vecFrom - vecAt).Normalize(); if (vecZAxis == vecUp) { SetIdentity(); m_m[0][3] = vecFrom.X(); m_m[1][3] = vecFrom.Y(); m_m[2][3] = vecFrom.Z(); } else { Vector vecXAxis = CrossProduct(vecUp, vecZAxis).Normalize(); Vector vecYAxis = CrossProduct(vecZAxis, vecXAxis); m_m[0][0] = vecXAxis.X(); m_m[0][1] = vecYAxis.X(); m_m[0][2] = vecZAxis.X(); m_m[0][3] = vecFrom.X(); m_m[1][0] = vecXAxis.Y(); m_m[1][1] = vecYAxis.Y(); m_m[1][2] = vecZAxis.Y(); m_m[1][3] = vecFrom.Y(); m_m[2][0] = vecXAxis.Z(); m_m[2][1] = vecYAxis.Z(); m_m[2][2] = vecZAxis.Z(); m_m[2][3] = vecFrom.Z(); m_m[3][0] = 0; m_m[3][1] = 0; m_m[3][2] = 0; m_m[3][3] = 1; m_type = TransformRotate | TransformTranslate; } return *this; }