int run_alps(int *steps) { int i,j,k,p; double temp_fitness[FITNESS_COUNT]; double temp_gene[GENE_COUNT]; int pareto_front[POP]; int pareto_count; begin = time(NULL); init_population(); // Initialise population. t = 0; goal_indiv = -1; mprintf(1, "preamble -> {expName -> %s, phaseCount -> %d, lobotomise -> %s, task -> %d, \n", exp_name, phase_count, lobotomise ? "True" : "False", task_index + 1); mprintf(1, "\ttmax -> %.2lf, fitnessType -> %d, runType -> %d, randomSeed -> %ld }\n", TIME_MAX, fitness_type, run_type, random_seed); mprintf(1, "alpsParams -> { layerCount -> %d, popPerLayer -> %d, " "popCount -> %d, mutProbability -> %.3f, maxSeconds -> %d }\n", LAYER_COUNT, POP_PER_LAYER, POP, mut_prob, MAX_SECONDS); fflush(stdout); for (p = 0, phase = 1; p < phase_count && elapsed_seconds() < MAX_SECONDS; p++, phase = p + 1) { if (p != 0) end_phase(p); start_phase(phase); for (i = 0; i < POP; i++) { // Evaluate every gene. evaluate(genes[i], fitness_matrix + FITNESS_INDEX(i)); } int met_goal = 0; for (j = 0; j < POP; j++) { if (is_goal_fitness(fitness_matrix + FITNESS_INDEX(j))) { met_goal = 1; goal_indiv = j; } } if (met_goal) continue; for (; t < MAX_OPT_STEPS && elapsed_seconds() < MAX_SECONDS; t++) { // Evaluate the pareto front for each layer. for (k = 0; k < LAYER_COUNT; k++) pareto_front_rowmajor(pareto_front + k * POP_PER_LAYER, fitness_matrix + k * FITNESS_COUNT * POP_PER_LAYER, POP_PER_LAYER, FITNESS_COUNT); // Grab a non-dominated individual. int a; // O(n) single pass to count and grab a random individual // that's on the pareto front. pareto_count=0; for (i = 0; i < POP; i++) if (pareto_front[i] && (rand() < 1./(double)++pareto_count)) a = i; k = LAYER_OF_INDIV(a); if (t % DISPLAY_FREQ == 0) { int n = FITNESS_INDEX(a); if (! quiet) printf("t = %5d, pi = %3d, a = %2d, k = %2d, N(PF) = %2d, f(a) = {%f, %f}, " "efail = %3d, esucc = %5d, secs = %4ld\n", t, a, ages[a], k, pareto_count, fitness_matrix[n], fitness_matrix[n + 1], eval_fail_count, eval_succ_count, elapsed_seconds()); fflush(stdout); } if (t % reset_freq == 0) { // Reset the bottom layer. for (i = 0; i < POP_PER_LAYER; i++) { // Try to dislogde in the layer above if it's in the pareto front. if (pareto_front[i]) try_dislodge(genes[i], fitness_matrix + FITNESS_LINDEX(0, i), ages[i], 1); init_gene(genes[i]); ages[i] = 0; } for (i = 0; i < POP_PER_LAYER; i++) evaluate(genes[i], fitness_matrix + FITNESS_INDEX(i)); pareto_front_rowmajor(pareto_front, fitness_matrix, POP_PER_LAYER, FITNESS_COUNT); } copy(genes[a], temp_gene); mutate(temp_gene); int age = t/POP; evaluate(temp_gene, temp_fitness); int new_i = try_dislodge(temp_gene, temp_fitness, age, k); if (is_goal_fitness(temp_fitness)) { if (new_i < 0) { printf("warning: goal individual not able to dislodge anyone in layer %d and up.\n", k); } goal_indiv = new_i; break; /* Goto next phase */ } } } if (t == MAX_OPT_STEPS || elapsed_seconds() > MAX_SECONDS) alps_status = ALPS_FAIL; else alps_status = ALPS_SUCC; end_phase(phase - 1); if (steps) *steps = t; return alps_status; }
void Action_Channel::Help() const { mprintf("\t<solute mask> [<solvent mask>] [out <file>] [dx <dx> [dy <dy>] [dz <dz>]]\n"); }
//finds OGL extension functions //returns number found int opengl_get_extensions() { int i, j, k, num_found = 0; ogl_extension *ext = NULL; ogl_function *func = NULL; OGL_extension_string = (char*)glGetString(GL_EXTENSIONS); for (i = 0; i < NUM_OGL_EXTENSIONS; i++) { ext = &GL_Extensions[i]; k = 0; while ( !ext->enabled && (k < ext->num_extensions) ) { if ( opengl_find_extension(ext->extension_name[k]) ) { // some extensions do not have functions if (!ext->num_functions) { mprintf((" Using extension \"%s\".\n", ext->extension_name[k])); ext->enabled = 1; num_found++; goto Next; } // we do have functions so check any/all of them for (j = 0; j < ext->num_functions; j++) { func = get_ogl_function( ext->function_names[j] ); if (func == NULL) break; if ( !func->function_ptr ) func->function_ptr = (ptr_u)GET_PROC_ADDRESS(func->function_name); if ( !func->function_ptr ) break; } if ( j != ext->num_functions ) { mprintf((" Found extension \"%s\", but can't find the required function \"%s()\". Extension will be disabled!\n", ext->extension_name[k], ext->function_names[j])); if (ext->required_to_run) Error( LOCATION, "The required OpenGL extension '%s' is not fully supported by your current driver version or graphics card.\n", ext->extension_name[k] ); } else { mprintf((" Using extension \"%s\".\n", ext->extension_name[k])); ext->enabled = 1; num_found++; } } else { // only report if unable to find when we have checked all available extension name variants if ( k+1 >= ext->num_extensions ) { mprintf((" Unable to find extension \"%s\".\n", ext->extension_name[k])); if (ext->required_to_run) Error( LOCATION, "The required OpenGL extension '%s' is not supported by your current driver version or graphics card.\n", ext->extension_name[k] ); } } // now move the the next extension name Next: k++; } } num_found += opengl_get_extensions_special(); mprintf(( "\n" )); return num_found; }
void generate_banked_curve(fix maxscale, vms_equation coeffs) { vms_vector vec_dir, tvec, b4r4t; vms_vector coord,prev_point; fix enddist, nextdist; int firstsegflag; fixang rangle, uangle, angle, scaled_ang; fix t; if (CurveNumSegs) { extract_up_vector_from_segment( Cursegp,&b4r4t ); uangle = vm_vec_delta_ang( &b4r4t, &r4t, &r4 ); if (uangle >= F1_0 * 1/8) uangle -= F1_0 * 1/4; if (uangle >= F1_0 * 1/8) uangle -= F1_0 * 1/4; if (uangle <= -F1_0 * 1/8) uangle += F1_0 * 1/4; if (uangle <= -F1_0 * 1/8) uangle += F1_0 * 1/4; // mprintf(0, "up angle %f\n", f2fl(uangle)*360); extract_right_vector_from_segment( Cursegp,&b4r4t ); rangle = vm_vec_delta_ang( &b4r4t, &r4t, &r4 ); if (rangle >= F1_0/8) rangle -= F1_0/4; if (rangle >= F1_0/8) rangle -= F1_0/4; if (rangle <= -F1_0/8) rangle += F1_0/4; if (rangle <= -F1_0/8) rangle += F1_0/4; // mprintf(0, "right angle %f\n", f2fl(rangle)*360); angle = uangle; if (abs(rangle) < abs(uangle)) angle = rangle; delete_curve(); coord = prev_point = p1; #define MAGIC_NUM 0.707*F1_0 if (maxscale) scaled_ang = fixdiv(angle,fixmul(maxscale,MAGIC_NUM)); mprintf((0, "scaled angle = %f\n", f2fl(scaled_ang))); t=0; tvec = r1save; firstsegflag = 1; enddist = F1_0; nextdist = 0; while ( enddist > fixmul( nextdist, 1.5*F1_0 )) { vms_matrix rotmat,rotmat2; vms_vector tdest; if (firstsegflag==1) firstsegflag=0; else extract_forward_vector_from_segment(Cursegp, &tvec); nextdist = vm_vec_mag(&tvec); // nextdist := distance to next point t = curve_dist(&coeffs, 3, t, &prev_point, nextdist); // t = argument at which function is forward vector magnitude units away from prev_point (in 3-space, not along curve) coord = evaluate_curve(&coeffs, 3, t); // coord := point about forward vector magnitude units away from prev_point enddist = vm_vec_dist(&coord, &p4); // enddist := distance from current to end point, vec_dir used as a temporary variable //vm_vec_normalize(vm_vec_sub(&vec_dir, &coord, &prev_point)); vm_vec_normalized_dir(&vec_dir, &coord, &prev_point); if (!med_attach_segment( Cursegp, &New_segment, Curside, AttachSide )) { med_extract_matrix_from_segment( Cursegp,&rotmat ); // rotmat := matrix describing orientation of Cursegp vm_vec_rotate(&tdest,&vec_dir,&rotmat); // tdest := vec_dir in reference frame of Cursegp vec_dir = tdest; vm_vec_ang_2_matrix(&rotmat2,&vec_dir,scaled_ang); // mprintf((0, "[ [%6.2f %6.2f %6.2f]", f2fl(rotmat2.m1), f2fl(rotmat2.m2), f2fl(rotmat2.m3))); // mprintf((0, " [%6.2f %6.2f %6.2f]", f2fl(rotmat2.m4), f2fl(rotmat2.m5), f2fl(rotmat2.m6))); // mprintf((0, " [%6.2f %6.2f %6.2f] ]\n", f2fl(rotmat2.m7), f2fl(rotmat2.m8), f2fl(rotmat2.m9))); med_rotate_segment( Cursegp, &rotmat2 ); prev_point = coord; Curside = Side_opposite[AttachSide]; CurveSegs[CurveNumSegs]=Cursegp; CurveNumSegs++; } } } }
void VOICEREC_execute_command(ISpPhrase *pPhrase, HWND hWnd) { SPPHRASE *pElements; // Get the phrase elements, one of which is the rule id we specified in // the grammar. Switch on it to figure out which command was recognized. if (SUCCEEDED(pPhrase->GetPhrase(&pElements))) { #ifndef NDEBUG if(DEBUG_ON) { WCHAR *pwszText; char szText[255]; int i; pPhrase->GetText(static_cast<ULONG>(SP_GETWHOLEPHRASE), static_cast<ULONG>(SP_GETWHOLEPHRASE), TRUE, &pwszText, NULL); memset(szText, 0, 255); for (i=0;i<254;i++) { if (*(pwszText + i) == 0) { break; } szText[i] = (char)(*(pwszText + i)); szText[i+1] = 0; } mprintf(( "recognized speech : %s \n", szText )); mprintf(( "speech Rule.ulId : %d \n", pElements->Rule.ulId )); mprintf(( "confidence: %f \n", pElements->pProperties->SREngineConfidence)); ::CoTaskMemFree(pwszText); } #endif int part1, part2, part3; part1 = part2 = part3 = -1; switch ( pElements->Rule.ulId ) { case VID_WingName: { part1 = pElements->pProperties->vValue.ulVal; if (pElements->pProperties->pNextSibling) { part2 = pElements->pProperties->pNextSibling->vValue.ulVal; if (pElements->pProperties->pNextSibling->pNextSibling) { part3 = pElements->pProperties->pNextSibling->pNextSibling->vValue.ulVal; } } if (part2 == -1) break; // no ship number or wing const wchar_t* valstr = pElements->pProperties->pszValue; char* wing_name = new char[wcslen(valstr)+1]; size_t j = 0; for (size_t i = 0; i < wcslen(valstr); i++) { int c = wctob(valstr[i]); if (c != EOF) { wing_name[j++] = static_cast<char>(c); } } wing_name[j] = '\0'; if (part2 == 0) { Msg_instance = wing_lookup(wing_name); delete[] wing_name; if (Msg_instance < 0) break; if(!(Player->flags & PLAYER_FLAGS_MSG_MODE)) { hud_squadmsg_toggle(); } if (hud_squadmsg_wing_valid(&Wings[Msg_instance])) hud_squadmsg_do_mode(SM_MODE_WING_COMMAND); } else { char shipName[NAME_LENGTH]; wing_bash_ship_name(shipName, wing_name, part2); delete[] wing_name; Msg_instance = ship_name_lookup(shipName); // Can't issue commands to yourself or to nobody if (Msg_instance < 0 || Msg_instance == Player_obj->instance) { break; } if(!(Player->flags & PLAYER_FLAGS_MSG_MODE)) { hud_squadmsg_toggle(); } if (hud_squadmsg_ship_valid(&Ships[Msg_instance])) hud_squadmsg_do_mode(SM_MODE_SHIP_COMMAND); } if (part3 == -1) break; } case VID_Action: { int action; if (part3 == -1) { action = pElements->pProperties->vValue.ulVal; } else { action = part3; } doVid_Action(action); break; } // These commands run no matter what, and will even bring up the menu case VID_TopMenu: { int action = pElements->pProperties->vValue.ulVal; bool msgWindow = false; if (Player->flags & PLAYER_FLAGS_MSG_MODE) { msgWindow = true; } // If the command window is not up, or it is and its a cancel request toggle if((msgWindow && action == VID_Cancel) || (!msgWindow && action != VID_Cancel)) { hud_squadmsg_toggle(); } switch(action) { case VID_Ships: hud_squadmsg_do_mode( SM_MODE_SHIP_SELECT ); break; case VID_Wings: hud_squadmsg_do_mode( SM_MODE_WING_SELECT ); break; case VID_AllFighters: case VID_AllWings: hud_squadmsg_msg_all_fighters(); // can have the action to perform spoken directly afterwards if (pElements->pProperties->pFirstChild) { doVid_Action(pElements->pProperties->pFirstChild->vValue.ulVal); } break; case VID_Reinforcements: hud_squadmsg_do_mode( SM_MODE_REINFORCEMENTS ); break; case VID_SupportShip: hud_squadmsg_do_mode( SM_MODE_REPAIR_REARM ); break; case VID_AbortSupport: hud_squadmsg_do_mode( SM_MODE_REPAIR_REARM_ABORT ); break; case VID_More: break; } break; } // phrases for transferring shield energy to different locations case VID_shields: { int action = pElements->pProperties->vValue.ulVal; switch(action) { case 0: button_function( SHIELD_XFER_TOP ); break; case 1: button_function( SHIELD_XFER_LEFT ); break; case 2: button_function( SHIELD_XFER_RIGHT ); break; case 3: button_function( SHIELD_XFER_BOTTOM ); break; case 4: button_function( SHIELD_EQUALIZE ); break; } break; } // basic cheat, phrase as a value equivalent to the defines in ControlConfig/ControlsConfig.h // it just calls the button_function with this value case VID_speed: case VID_targeting: case VID_other: { int action = pElements->pProperties->vValue.ulVal; if (action > -1) { button_function( action ); } break; } // nearly the same as the previous except it has some extra entries for // maximising/minimising energy case VID_power: { int action = pElements->pProperties->vValue.ulVal; if (action >= INCREASE_WEAPON && action <= ETS_EQUALIZE) { button_function( action ); } else { // this is for the max engines etc. for (int i=1; i<7; i++) { button_function( action - 132 ); } } break; } } // Free the pElements memory which was allocated for us ::CoTaskMemFree(pElements); } }
/** \return 1 if a new dihedral should be tried, 0 if no clashes * \return -1 if further rotations will not help. */ int Exec_PermuteDihedrals::CheckResidue( Frame const& FrameIn, Topology const& topIn, PermuteDihedralsType const& dih, int nextres, double& clash ) { int resnumIn = dih.resnum; int rstart = ResCheck_[ resnumIn ].start; int rstop = ResCheck_[ resnumIn ].stop; int rcheck = ResCheck_[ resnumIn ].checkatom; // Check for clashes with self # ifdef DEBUG_PERMUTEDIHEDRALS mprintf("\tChecking residue %i\n",resnumIn+1); mprintf("\tATOMS %i to %i\n",rstart+1,rstop); # endif for (int atom1 = rstart; atom1 < rstop - 1; atom1++) { for (int atom2 = atom1 + 1; atom2 < rstop; atom2++) { // Skip bonded atoms bool isBonded = false; for (Atom::bond_iterator bndatm = topIn[atom1].bondbegin(); bndatm != topIn[atom1].bondend(); ++bndatm) if (*bndatm == atom2) { isBonded = true; break; } if (!isBonded) { double atomD2 = DIST2_NoImage(FrameIn.XYZ(atom1), FrameIn.XYZ(atom2)); if (atomD2 < cutoff_) { # ifdef DEBUG_PERMUTEDIHEDRALS mprintf("\t\tCurrent Res %i Atoms %s and %s are close (%.3lf)\n", resnumIn+1, topIn.AtomMaskName(atom1).c_str(), topIn.AtomMaskName(atom2).c_str(), sqrt(atomD2)); # endif clash = atomD2; return 1; } } } } // Check for clashes with previous residues, as well as clashes up to and // including the next residue in which a dihedral will be rotated. for (int res = 0; res <= nextres; res++) { if (res == resnumIn) continue; int rstart2 = ResCheck_[ res ].start; int rstop2 = ResCheck_[ res ].stop; int rcheck2 = ResCheck_[ res ].checkatom; double resD2 = DIST2_NoImage(FrameIn.XYZ(rcheck), FrameIn.XYZ(rcheck2)); // If residues are close enough check each atom if (resD2 < rescutoff_) { # ifdef DEBUG_PERMUTEDIHEDRALS mprintf("\tRES %i ATOMS %i to %i\n",res+1,rstart2+2,rstop2); # endif for (int atom1 = rstart; atom1 < rstop; atom1++) { for (int atom2 = rstart2; atom2 < rstop2; atom2++) { double D2 = DIST2_NoImage(FrameIn.XYZ(atom1), FrameIn.XYZ(atom2)); if (D2 < cutoff_) { # ifdef DEBUG_PERMUTEDIHEDRALS mprintf("\t\tResCheck %i Atoms %s and %s are close (%.3lf)\n", res+1, topIn.TruncResAtomName(atom1).c_str(), topIn.TruncResAtomName(atom2).c_str(), sqrt(D2)); # endif clash = D2; // If the clash involves any atom that will not be moved by further // rotation, indicate it is not possible to resolve clash by // more rotation by returning -1. //if (atom1 == dih.atom2 || atom1 == dih.atom1) return -1; for (std::vector<int>::const_iterator ca = dih.checkAtoms.begin(); ca != dih.checkAtoms.end(); ca++) { if (atom1 == *ca) return -1; } return 1; } } } } } return 0; }
// Exec_PermuteDihedrals::Execute() Exec::RetType Exec_PermuteDihedrals::Execute(CpptrajState& State, ArgList& argIn) { mode_ = INTERVAL; // Get Keywords - first determine mode if (argIn.hasKey("random")) mode_ = RANDOM; else if (argIn.hasKey("interval")) mode_ = INTERVAL; // Get input COORDS set std::string setname = argIn.GetStringKey("crdset"); if (setname.empty()) { mprinterr("Error: Specify COORDS dataset name with 'crdset'.\n"); return CpptrajState::ERR; } DataSet_Coords* CRD = (DataSet_Coords*)State.DSL().FindCoordsSet( setname ); if (CRD == 0) { mprinterr("Error: Could not find COORDS set '%s'\n", setname.c_str()); return CpptrajState::ERR; } mprintf(" PERMUTEDIHEDRALS: Using COORDS '%s'\n", CRD->legend()); // Get residue range Range resRange; resRange.SetRange(argIn.GetStringKey("resrange")); if (!resRange.Empty()) resRange.ShiftBy(-1); // User res args start from 1 mprintf("\tPermutating dihedrals in"); if (resRange.Empty()) mprintf(" all solute residues.\n"); else mprintf(" residue range [%s]\n", resRange.RangeArg()); // Determine which angles to search for DihedralSearch dihSearch; dihSearch.SearchForArgs(argIn); // If nothing is enabled, enable all dihSearch.SearchForAll(); mprintf("\tSearching for types:"); dihSearch.PrintTypes(); mprintf("\n"); // Setup output trajectory outframe_ = 0; std::string outfilename = argIn.GetStringKey("outtraj"); if (!outfilename.empty()) { mprintf("\tCoordinates output to '%s'\n", outfilename.c_str()); Topology* outtop = State.DSL().GetTopology( argIn ); if (outtop == 0) { mprinterr("Error: No topology for output traj.\n"); return CpptrajState::ERR; } // Setup output trajectory FIXME: Correct frames for # of rotations if (outtraj_.PrepareTrajWrite(outfilename, argIn, CRD->TopPtr(), CRD->CoordsInfo(), CRD->Size(), TrajectoryFile::UNKNOWN_TRAJ)) return CpptrajState::ERR; } // Setup output coords outfilename = argIn.GetStringKey("crdout"); if (!outfilename.empty()) { mprintf("\tCoordinates saved to set '%s'\n", outfilename.c_str()); crdout_ = (DataSet_Coords_CRD*)State.DSL().AddSet(DataSet::COORDS, outfilename); if (crdout_ == 0) return CpptrajState::ERR; crdout_->CoordsSetup( CRD->Top(), CRD->CoordsInfo() ); } // Get specific mode options. double interval_in_deg = 60.0; if ( mode_ == INTERVAL ) { interval_in_deg = argIn.getNextDouble(60.0); mprintf("\tDihedrals will be rotated at intervals of %.2f degrees.\n", interval_in_deg); } else if (mode_ == RANDOM) { check_for_clashes_ = argIn.hasKey("check"); checkAllResidues_ = argIn.hasKey("checkallresidues"); cutoff_ = argIn.getKeyDouble("cutoff",0.8); rescutoff_ = argIn.getKeyDouble("rescutoff",10.0); backtrack_ = argIn.getKeyInt("backtrack",4); increment_ = argIn.getKeyInt("increment",1); max_factor_ = argIn.getKeyInt("maxfactor",2); int iseed = argIn.getKeyInt("rseed",-1); // Output file for # of problems DataFile* problemFile = State.DFL().AddDataFile(argIn.GetStringKey("out"), argIn); // Dataset to store number of problems number_of_problems_ = State.DSL().AddSet(DataSet::INTEGER, argIn.GetStringNext(),"Nprob"); if (number_of_problems_==0) return CpptrajState::ERR; // Add dataset to data file list if (problemFile != 0) problemFile->AddDataSet(number_of_problems_); // Check validity of args if (cutoff_ < Constants::SMALL) { mprinterr("Error: cutoff too small.\n"); return CpptrajState::ERR; } if (rescutoff_ < Constants::SMALL) { mprinterr("Error: rescutoff too small.\n"); return CpptrajState::ERR; } if (backtrack_ < 0) { mprinterr("Error: backtrack value must be >= 0\n"); return CpptrajState::ERR; } if ( increment_<1 || (360 % increment_)!=0 ) { mprinterr("Error: increment must be a factor of 360.\n"); return CpptrajState::ERR; } // Calculate max increment max_increment_ = 360 / increment_; // Seed random number gen RN_.rn_set( iseed ); // Print info mprintf("\tDihedrals will be rotated to random values.\n"); if (iseed==-1) mprintf("\tRandom number generator will be seeded using time.\n"); else mprintf("\tRandom number generator will be seeded using %i\n",iseed); if (check_for_clashes_) { mprintf("\tWill attempt to recover from bad steric clashes.\n"); if (checkAllResidues_) mprintf("\tAll residues will be checked.\n"); else mprintf("\tResidues up to the currenly rotating dihedral will be checked.\n"); mprintf("\tAtom cutoff %.2f, residue cutoff %.2f, backtrack = %i\n", cutoff_, rescutoff_, backtrack_); mprintf("\tWhen clashes occur dihedral will be incremented by %i\n",increment_); mprintf("\tMax # attempted rotations = %i times number dihedrals.\n", max_factor_); } // Square cutoffs to compare to dist^2 instead of dist cutoff_ *= cutoff_; rescutoff_ *= rescutoff_; // Increment backtrack by 1 since we need to skip over current res ++backtrack_; // Initialize CheckStructure if (checkStructure_.SeparateInit( false, "*", "", "", 0.8, 1.15, false, State.DFL() )) { mprinterr("Error: Could not set up structure check.\n"); return CpptrajState::ERR; } // Set up CheckStructure for this parm (false = nobondcheck) if (checkStructure_.SeparateSetup(CRD->Top(), CRD->CoordsInfo().TrajBox().Type(), false) != Action::OK) return CpptrajState::ERR; } // Determine from selected mask atoms which dihedrals will be rotated. PermuteDihedralsType dst; // If range is empty (i.e. no resrange arg given) look through all // solute residues. Range actualRange; if (resRange.Empty()) actualRange = CRD->Top().SoluteResidues(); else actualRange = resRange; // Search for dihedrals if (dihSearch.FindDihedrals(CRD->Top(), actualRange)) return CpptrajState::ERR; // For each found dihedral, set up mask of atoms that will move upon // rotation. Also set up mask of atoms in this residue that will not // move, including atom2. if (debug_>0) mprintf("DEBUG: Dihedrals:\n"); for (DihedralSearch::mask_it dih = dihSearch.begin(); dih != dihSearch.end(); ++dih) { dst.checkAtoms.clear(); // Set mask of atoms that will move during dihedral rotation. dst.Rmask = DihedralSearch::MovingAtoms(CRD->Top(), dih->A1(), dih->A2()); // If randomly rotating angles, check for atoms that are in the same // residue as A1 but will not move. They need to be checked for clashes // since further rotations will not help them. if (mode_ == RANDOM && check_for_clashes_) { CharMask cMask( dst.Rmask.ConvertToCharMask(), dst.Rmask.Nselected() ); int a1res = CRD->Top()[dih->A1()].ResNum(); for (int maskatom = CRD->Top().Res(a1res).FirstAtom(); maskatom < CRD->Top().Res(a1res).LastAtom(); ++maskatom) if (!cMask.AtomInCharMask(maskatom)) dst.checkAtoms.push_back( maskatom ); dst.checkAtoms.push_back(dih->A1()); // TODO: Does this need to be added first? // Since only the second atom and atoms it is bonded to move during // rotation, base the check on the residue of the second atom. dst.resnum = a1res; } dst.atom0 = dih->A0(); // FIXME: This duplicates info dst.atom1 = dih->A1(); dst.atom2 = dih->A2(); dst.atom3 = dih->A3(); BB_dihedrals_.push_back(dst); // DEBUG: List dihedral info. if (debug_ > 0) { mprintf("\t%s-%s-%s-%s\n", CRD->Top().TruncResAtomName(dih->A0()).c_str(), CRD->Top().TruncResAtomName(dih->A1()).c_str(), CRD->Top().TruncResAtomName(dih->A2()).c_str(), CRD->Top().TruncResAtomName(dih->A3()).c_str() ); if (debug_ > 1 && mode_ == RANDOM && check_for_clashes_) { mprintf("\t\tCheckAtoms="); for (std::vector<int>::const_iterator ca = dst.checkAtoms.begin(); ca != dst.checkAtoms.end(); ++ca) mprintf(" %i", *ca + 1); mprintf("\n"); } if (debug_ > 2) { mprintf("\t\t"); dst.Rmask.PrintMaskAtoms("Rmask:"); } } } // Set up simple structure check. First step is coarse; check distances // between a certain atom in each residue (first, COM, CA, some other atom?) // to see if residues are in each others neighborhood. Second step is to // check the atoms in each close residue. if (check_for_clashes_) { ResidueCheckType rct; int res = 0; for (Topology::res_iterator residue = CRD->Top().ResStart(); residue != CRD->Top().ResEnd(); ++residue) { rct.resnum = res++; rct.start = residue->FirstAtom(); rct.stop = residue->LastAtom(); rct.checkatom = rct.start; ResCheck_.push_back(rct); } } // Perform dihedral permute Frame currentFrame = CRD->AllocateFrame(); for (unsigned int set = 0; set != CRD->Size(); set++) { CRD->GetFrame(set, currentFrame); int n_problems = 0; switch (mode_) { case RANDOM: RandomizeAngles(currentFrame, CRD->Top()); // Check the resulting structure n_problems = checkStructure_.CheckOverlap( set+1, currentFrame, CRD->Top() ); //mprintf("%i\tResulting structure has %i problems.\n",frameNum,n_problems); number_of_problems_->Add(set, &n_problems); if (outtraj_.IsInitialized()) outtraj_.WriteSingle(outframe_++, currentFrame); if (crdout_ != 0) crdout_->AddFrame( currentFrame ); break; case INTERVAL: IntervalAngles(currentFrame, CRD->Top(), interval_in_deg); break; } } if (outtraj_.IsInitialized()) outtraj_.EndTraj(); return CpptrajState::OK; }
/** * Compiles a new shader, and creates an opengl_shader_t that will be put into the GL_shader vector * if compilation is successful. * * @param sdr Identifier defined with the program we wish to compile * @param flags Combination of SDR_* flags */ int opengl_compile_shader(shader_type sdr, uint flags) { int sdr_index = -1; int empty_idx; opengl_shader_t new_shader; Assert(sdr < NUM_SHADER_TYPES); opengl_shader_type_t *sdr_info = &GL_shader_types[sdr]; mprintf(("Compiling new shader:\n")); mprintf((" %s\n", sdr_info->description)); // figure out if the variant requested needs a geometry shader bool use_geo_sdr = false; // do we even have a geometry shader? if ( sdr_info->geo != NULL ) { for (int i = 0; i < GL_num_shader_variants; ++i) { opengl_shader_variant_t *variant = &GL_shader_variants[i]; if (variant->type_id == sdr && flags & variant->flag && variant->use_geometry_sdr) { use_geo_sdr = true; break; } } } auto vertex_content = opengl_get_shader_content(sdr_info->type_id, sdr_info->vert, flags); auto fragment_content = opengl_get_shader_content(sdr_info->type_id, sdr_info->frag, flags); SCP_vector<SCP_string> geom_content; if ( use_geo_sdr ) { if (!Is_Extension_Enabled(OGL_EXT_GEOMETRY_SHADER4)) { return -1; } // read geometry shader geom_content = opengl_get_shader_content(sdr_info->type_id, sdr_info->geo, flags); Current_geo_sdr_params = &sdr_info->geo_sdr_info; } new_shader.program_id = opengl_shader_create(vertex_content, fragment_content, geom_content); if (!new_shader.program_id) { return -1; } new_shader.shader = sdr_info->type_id; new_shader.flags = flags; opengl_shader_set_current(&new_shader); // initialize uniforms and attributes for ( int i = 0; i < sdr_info->num_uniforms; ++i ) { opengl_shader_init_uniform( sdr_info->uniforms[i] ); } for (int i = 0; i < sdr_info->num_attributes; ++i) { opengl_shader_init_attribute(sdr_info->attributes[i]); } // if this shader is POST_PROCESS_MAIN, hack in the user-defined flags if ( sdr_info->type_id == SDR_TYPE_POST_PROCESS_MAIN ) { opengl_post_init_uniforms(flags); } mprintf(("Shader Variant Features:\n")); // initialize all uniforms and attributes that are specific to this variant for ( int i = 0; i < GL_num_shader_variants; ++i ) { opengl_shader_variant_t &variant = GL_shader_variants[i]; if ( sdr_info->type_id == variant.type_id && variant.flag & flags ) { for (int j = 0; j < variant.num_uniforms; ++j) { opengl_shader_init_uniform(variant.uniforms[j]); } for (int j = 0; j < variant.num_attributes; ++j) { opengl_shader_init_attribute(variant.attributes[j]); } mprintf((" %s\n", variant.description)); } } opengl_shader_set_current(); // add it to our list of embedded shaders // see if we have empty shader slots empty_idx = -1; for ( int i = 0; i < (int)GL_shader.size(); ++i ) { if ( GL_shader[i].shader == NUM_SHADER_TYPES ) { empty_idx = i; break; } } // then insert it at an empty slot or at the end if ( empty_idx >= 0 ) { GL_shader[empty_idx] = new_shader; sdr_index = empty_idx; } else { sdr_index = GL_shader.size(); GL_shader.push_back(new_shader); } return sdr_index; }
void * tbSlave (ProcessData * pData, WavesData * wData) { MOATypeInd localCellIndex, maxlocalCellIndex; MOATypeDimn i; int MPI_return, isLower, done = 0; MPI_Request request; MPI_Status status; char msg[MID_MESSAGE_SIZE]; TracebackData * tbData; tbData = NULL; if (initTBData(&tbData, pData->seqNum, pData->seqLen) != 0) { printf ("Failed to allocate memory for trace back structure. Exiting\n"); return NULL; } if (AlignmentType == Local) sendmaxCellScore (pData, wData, tbData); tbData->aSeqLen = mcalloc ((MOATypeInd) 1, (MOATypeInd) sizeof *(tbData->aSeqLen)); tbData->algnseq = mmalloc ((MOATypeInd) sizeof *(tbData->algnseq)); tbData->pathParts = 1; tbData->algnseq[0] = NULL; tbData->algnseq[0] = mmalloc (tbData->seqNum * sizeof *(tbData->algnseq[0])); while (done < 2) { /*receive tracing flag, 0: trace back, Otherwise: finish & exit*/ #ifndef NDEBUG mprintf (3, "before receive new flag from master", 1); #endif /*1. Receive flag */ MPI_return = MPI_Recv (&done, 1, MPI_INT, 0, 2, MOAMSA_COMM_WORLD, &status); #ifndef NDEBUG sprintf(msg, "DSTB received flag %d \n", done); mprintf(3, msg, 1); #endif /*Check tracing flag (done = 0)*/ if (done == 0) { /*2. receive starting global index*/ MPI_return = MPI_Recv (tbData->maxCellIndex, tbData->seqNum, MPI_LONG_LONG, 0, 3, MOAMSA_COMM_WORLD, &status); #ifndef NDEBUG printf ("[%d] Received maxCellIndex { %lld", myProcid, tbData->maxCellIndex[0]); for (i=1;i<tbData->seqNum;i++) printf (", %lld", tbData->maxCellIndex[i]); printf ("}\n"); fflush(stdout); sprintf(msg, "DSTB received maxCellIndex {%lld", tbData->maxCellIndex[0]); for (i=1;i<tbData->seqNum;i++) sprintf (msg, "%s, %lld", msg, tbData->maxCellIndex[i]); sprintf (msg, "}\n", msg); mprintf(3, msg, 1); #endif /*Perform local Partitions trace back*/ tbData->aSeqLen[0] = traceBack (pData, wData, tbData); #ifndef NDEBUG sprintf(msg, "DSTB returned path of length %ld \n", tbData->aSeqLen[0]); mprintf(3, msg, 1); #endif /*3. send partital alignment length*/ MPI_return = MPI_Send (&tbData->aSeqLen[0], 1, MPI_LONG_LONG, 0, 4, MOAMSA_COMM_WORLD); #ifndef NDEBUG printf("[%d] sent length %ld MPI_return %d \n", myProcid, tbData->aSeqLen[0], MPI_return); fflush(stdout); #endif /*4. send the partital alignment itself*/ for (i=0;i<tbData->seqNum;i++) { tbData->algnseq[0][i][tbData->aSeqLen[0]] = '\0'; MPI_return = MPI_Send (tbData->algnseq[0][i], tbData->aSeqLen[0], MPI_CHAR, 0, 5, MOAMSA_COMM_WORLD); #ifndef NDEBUG sprintf(msg, " sent aligned seq for seq %lld MPI_return %d = %s ", i, MPI_return, tbData->algnseq[0][i]); mprintf(3, msg, 1); printf("[%d] sent aligned seq for seq %lld MPI_return %d = %s\n", myProcid, i, MPI_return, tbData->algnseq[0][i]); fflush(stdout); #endif } #ifndef NDEBUG mprintf(3, "\n", 1); #endif /*5. send the last global index in this partial alignment to Master*/ MPI_return = MPI_Send (tbData->maxCellIndex, tbData->seqNum, MPI_LONG_LONG, 0, 7, MOAMSA_COMM_WORLD); #ifndef NDEBUG printf ("[%d] sent MPI_return %d maxCellIndex { %lld", myProcid, MPI_return, tbData->maxCellIndex[0]); for (i=1;i<tbData->seqNum;i++) printf (", %lld", tbData->maxCellIndex[i]); printf ("}\n"); fflush(stdout); sprintf(msg, "after send maxCellIndex {%ld", tbData->maxCellIndex[0]); mprintf(3, msg, 1); for (i=1;i<tbData->seqNum;i++) { sprintf(msg, ", %ld", tbData->maxCellIndex[i]); mprintf(3, msg, 1); } mprintf(3, "}\n", 1); #endif /*6. send the next Processor where a next remote score was found from this partial alignment to Master*/ MPI_return = MPI_Send (&tbData->currProc, 1, MPI_INT, 0, 8, MOAMSA_COMM_WORLD); #ifndef NDEBUG printf("[%d] sent new tbData->currProc = %d MPI_return %d \n", myProcid, tbData->currProc, MPI_return); fflush(stdout); sprintf(msg, "after send next proc %d\n", tbData->currProc); mprintf(3, msg, 1); #endif } } if (tbData != NULL) freetbData(&tbData); return NULL; }
shared_ptr<ScheduleTask> ZenScheduler::scheduleUS(const std::string &description, MWTime initial_delay, MWTime repeat_interval, int ntimes, boost::function<void *()> _functor, int _priority, MWTime _warn_slop_us, MWTime _fail_slop_us, MissedExecutionBehavior _behav){ MWTime start_time = the_clock->getCurrentTimeUS(); boost::mutex::scoped_lock lock(scheduler_lock); nscheduled++; long node_id = nscheduled; pthread_t thread; shared_ptr<Scheduler> self_shared_ptr(component_shared_from_this<Scheduler>()); // Build up a description of the task to schedule shared_ptr<ZenScheduleTask> *task_ptr = new shared_ptr<ZenScheduleTask>(new ZenScheduleTask(description, node_id, self_shared_ptr, _functor, start_time, initial_delay, repeat_interval, ntimes, _priority, _behav, _warn_slop_us, _fail_slop_us, -1)); // This pointer hand-off is necessary to get the task description passed // into the scheduled function (that function will call delete on the // the extra copy of the shared_ptr) // shared_ptr<ZenScheduleTask> *task_ptr = // new shared_ptr<ZenScheduleTask>(); // *task_ptr = task; shared_ptr<ZenScheduleTask> task = *task_ptr; int status = pthread_create(&thread, NULL, zenScheduledExecutionThread, task_ptr); if(status != 0){ switch(status){ case EAGAIN: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "System lacks resources necessary to create another scheduling thread"); break; case EINVAL: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Invalid thread parameters during new thread creation"); break; case EPERM: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Permissions error on new thread creation"); break; } shared_ptr<ScheduleTask> empty; return empty; } pthread_detach(thread); task->setThread(thread); struct sched_param sp; memset(&sp, 0, sizeof(struct sched_param)); #ifdef LOW_PRIORITY_MODE sp.sched_priority = 0; #else sp.sched_priority=_priority; #endif #ifdef REALTIME_SCHEDULER status = pthread_setschedparam(thread, SCHED_FIFO, &sp); #else status = pthread_setschedparam(thread, SCHED_RR, &sp); #endif if(status != 0){ switch(status){ case EINVAL: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Failed to set thread priority: settings invalid"); break; case EFAULT: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Failed to set thread priority: invalid param pointer"); break; case ENOTSUP: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Failed to set thread priority: unsupported setting"); break; case ESRCH: mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Failed to set thread priority: thread not running"); break; } } // Keep track of the task here in the scheduler (so that we can cancel // it later if we need to stop everything). //all_tasks.push_back(task); if(VERBOSE_SCHEDULER) mprintf("%d tasks successfully scheduled", nscheduled); // Return a shared_ptr to the task so that the party that scheduled // this task can cancel it if needed. shared_ptr<ScheduleTask> returntask = boost::dynamic_pointer_cast<ScheduleTask, ZenScheduleTask>(task); return returntask; }
void *zenScheduledExecutionThread(void *arglist){ // Hand-off the task description shared_ptr<ZenScheduleTask> *task_ptr = (shared_ptr<ZenScheduleTask> *)arglist; shared_ptr<ZenScheduleTask> task = *task_ptr; delete task_ptr; // moved until end for speediness //task->heartbeat(); if(VERBOSE_SCHEDULER) mprintf("Scheduled thread spawned %p", task.get()); // Unpack the task description boost::function<void *()> functor = task->getFunctor(); int ntimes = task->getNTimes(); MWTime initial_delay_us = task->getInitialDelayUS(); MWTime repeat_interval_us = task->getRepeatIntervalUS(); if(VERBOSE_SCHEDULER) mprintf(" ****** repeat_interval_us = %lu %p", (unsigned long)repeat_interval_us, task.get()); MWTime start_time_us = task->getStartTimeUS(); MissedExecutionBehavior behavior = task->getMissedExecutionBehavior(); int priority = task->getPriority(); MWTime warning_slop_us = task->getWarningSlopUS(); int fail_slop_us = task->getFailureSlopUS(); MWTime computation_time_us = task->getComputationTimeUS(); MWTime next_us; long ndone = 0; // Go realtime, if requested if(VERBOSE_SCHEDULER) mprintf("Computation time = %lld", computation_time_us); if(computation_time_us > 0LL){ //#if (defined(__ppc__) && defined(__APPLE__)) //mprintf("%d", get_bus_speed); #ifndef LOW_PRIORITY_MODE set_realtime(((double)get_bus_speed() * (double)repeat_interval_us) / 1000000.0, ((double)get_bus_speed() * (double)computation_time_us) / 1000000.0, ((double)get_bus_speed() * (double)repeat_interval_us) / 1000000.0); #endif //#endif } else { #if REALTIME_SCHEDULER #ifndef LOW_PRIORITY_MODE int didit = set_realtime(priority); if(didit){ //fprintf(stderr, "Scheduler went realtime. Rock on.\n"); //fflush(stderr); } else { fprintf(stderr,"Scheduler didn't go realtime. Bummer.\n"); fflush(stderr); } #endif #endif } MWTime now_us = task->getScheduler()->getClock()->getCurrentTimeUS(); //cerr << "Startup latency: " << now_us - start_time_us << endl; MWTime time_to_first_shot = (start_time_us + initial_delay_us) - now_us; // Sleep if there is an initial delay if(time_to_first_shot > 0){ task->getScheduler()->getClock()->sleepUS(time_to_first_shot); } // Compute the next scheduled execution time next_us = start_time_us + initial_delay_us + repeat_interval_us; if(VERBOSE_SCHEDULER) mprintf("Scheduled thread entering main loop (%ld done, %d total) %p", ndone, ntimes, task.get()); while(task->isActive() && (ntimes == M_REPEAT_INDEFINITELY || ndone < ntimes)){ //task->heartbeat(); // ********************* // Execute the payload // ********************* if(VERBOSE_SCHEDULER){ mprintf("Scheduled function called " "(main loop, %ld done / %d total) %p", ndone, ntimes, task.get()); } now_us = task->getScheduler()->getClock()->getCurrentTimeUS(); functor(); if(VERBOSE_SCHEDULER){ mprintf("Scheduled function returned " "(main loop) %p", task.get()); } if(fail_slop_us > (MWTime)0 && now_us - next_us > fail_slop_us){ if(!SILENCE_SCHEDULE_WARNINGS){ merror(M_SCHEDULER_MESSAGE_DOMAIN, "Scheduled task (%s) not on time (off by %lld; task = %p; priority= %d)", task->getDescription().c_str(), now_us - next_us, task.get(), task->getPriority()); } } else if(warning_slop_us > (MWTime)0 && now_us - next_us > warning_slop_us){ if (!SILENCE_SCHEDULE_WARNINGS) { mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Scheduled task (%s) not on time (off by %lld; task = %p; priority=%d)", task->getDescription().c_str(), now_us - next_us, task.get(), task->getPriority()); } } // one closer to being done... ndone++; // communicate back with the task object task->setNDone(ndone); if(ntimes != M_REPEAT_INDEFINITELY && ndone >= ntimes){ if(VERBOSE_SCHEDULER) mprintf("Scheduled task has completed %ld executions, quitting %p", ndone, task.get()); break; } if(!task->isActive()){ if(VERBOSE_SCHEDULER) mprintf("Scheduled execution deactivated (2) %p", task.get()); break; } // this is when the next one should happen next_us = start_time_us + initial_delay_us + (ndone)*repeat_interval_us; now_us = task->getScheduler()->getClock()->getCurrentTimeUS(); // are we going too slow? // if (warned) mprintf("DROP decision values: now: %d next: %d now-next: %d ms repeat interval %d ms", // (long)(now_us/1000), (long)(next_us/1000), (long)((now_us - next_us)/1000), (long)(repeat_interval_us/1000)); // JJD change Jan 30, 2007. // if when the NEXT one should happen is already more than the repeat_interval behind, then we are already too late! // This is partly how we can get into the state with a bunch of warnings, but no correction by dropping. // If warnings are less than this, then it IS proper behavior to keep spitting out the warnings -- it is up to the person scheduling // things to set the warning level appropriately (i.e. greater than the repeat interval plus some slop to deal with delays inside this routine). //if((now_us - next_us) > (repeat_interval_us + warning_slop_us)) { // DDC old test if((now_us - next_us) > (repeat_interval_us)) { // JJD new test Jan 30, 2007 //if (now_us > next_us) { // DDC Feb 12, 3007 if(VERBOSE_SCHEDULER){ mprintf("Thread not keeping up (off by %ld usec: now = %lu, next = %lu repeat = %lu; priority = %d) %p", (long)(now_us - next_us), (unsigned long)now_us, (unsigned long)next_us, (unsigned long)repeat_interval_us, priority, task.get()); } switch(behavior){ case M_MISSED_EXECUTION_DROP: if(repeat_interval_us){ if(VERBOSE_SCHEDULER) mprintf("Dropping (ndone was: %ld) %p", ndone, task.get()); ndone += 0 + (int)((now_us - next_us) / repeat_interval_us); //mprintf("((now_us - next_us) / repeat_interval_us) = %lld", ((now_us - next_us) / repeat_interval_us)); // move on if(warning_slop_us > (MWTime)0){ if (!SILENCE_SCHEDULE_WARNINGS){ mwarning(M_SCHEDULER_MESSAGE_DOMAIN, "Scheduled task (%s) falling behind, dropping %d " "scheduled executions " "(priority = %d, interval = %lld, task = %p)", task->getDescription().c_str(), 1 + (int)((now_us - next_us) / repeat_interval_us), priority, repeat_interval_us, task.get()); //lastWarnTimeUS = now_us; if(task.get() == NULL){ merror(M_SCHEDULER_MESSAGE_DOMAIN, "NULL task: something is very wrong"); } } } } break; case M_MISSED_EXECUTION_CATCH_UP: // go go go.... continue; case M_MISSED_EXECUTION_FAIL: merror(M_SCHEDULER_MESSAGE_DOMAIN, "Scheduled execution failed to keep up"); // TODO: put on the brakes break; } } next_us = start_time_us + initial_delay_us + ((MWTime)(ndone))*repeat_interval_us; if((next_us - now_us) > 0){ if(VERBOSE_SCHEDULER) mprintf("Scheduled thread sleeping... (2: %lld) %p", (next_us - now_us), task.get()); task->getScheduler()->getClock()->sleepUS(next_us - now_us); } } task->getScheduler()->removeTask(task->getNodeID()); if(VERBOSE_SCHEDULER) mprintf("Scheduled thread ending... %p", task.get()); return 0; }
std::unique_ptr<os::OpenGLContext> MFCGraphicsOperations::createOpenGLContext(os::Viewport* port, const os::OpenGLContextAttributes& ctx) { auto mfcView = reinterpret_cast<MFCViewport*>(port); auto temp_ctx = wglCreateContext(mfcView->getHDC()); if (!temp_ctx) { mprintf(("Unable to create fake context for OpenGL W32!\n")); return nullptr; } if (!wglMakeCurrent(mfcView->getHDC(), temp_ctx)) { mprintf(("Unable to make current thread for OpenGL W32!\n")); if (!wglDeleteContext(temp_ctx)) { mprintf(("Failed to delete render context!")); } return nullptr; } if (!gladLoadWGLLoader(gladWGLLoader, mfcView->getHDC())) { mprintf(("Failed to load WGL functions!\n")); wglMakeCurrent(nullptr, nullptr); if (!wglDeleteContext(temp_ctx)) { mprintf(("Failed to delete render context!")); } return nullptr; } if (!GLAD_WGL_ARB_create_context) { // No support for 3.x if (ctx.major_version >= 3) { mprintf(("Can't create requested OpenGL context!\n")); wglMakeCurrent(nullptr, nullptr); if (!wglDeleteContext(temp_ctx)) { mprintf(("Failed to delete fake context!")); } return nullptr; } // Major version is low enough -> just use the fake context return std::unique_ptr<os::OpenGLContext>(new MFCOpenGLContext(temp_ctx)); } SCP_vector<int> attrib_list; attrib_list.push_back(WGL_CONTEXT_MAJOR_VERSION_ARB); attrib_list.push_back(ctx.major_version); attrib_list.push_back(WGL_CONTEXT_MINOR_VERSION_ARB); attrib_list.push_back(ctx.minor_version); if (GLAD_WGL_ARB_create_context_profile) { attrib_list.push_back(WGL_CONTEXT_PROFILE_MASK_ARB); attrib_list.push_back(ctx.profile == os::OpenGLProfile::Core ? WGL_CONTEXT_CORE_PROFILE_BIT_ARB : WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB); } int flags = 0; if (ctx.flags[os::OpenGLContextFlags::Debug]) { flags |= WGL_CONTEXT_DEBUG_BIT_ARB; } if (ctx.flags[os::OpenGLContextFlags::ForwardCompatible]) { flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } if (flags != 0) { attrib_list.push_back(WGL_CONTEXT_FLAGS_ARB); attrib_list.push_back(flags); } attrib_list.push_back(0); auto attrib_ctx = wglCreateContextAttribsARB(mfcView->getHDC(), nullptr, attrib_list.data()); // We don't need the fake context anymore wglMakeCurrent(nullptr, nullptr); if (!wglDeleteContext(temp_ctx)) { mprintf(("Failed to delete fakse context!")); } if (attrib_ctx == nullptr) { mprintf(("Failed to create OpenGL context!\n")); return nullptr; } if (!wglMakeCurrent(mfcView->getHDC(), attrib_ctx)) { mprintf(("Unable to make current thread for OpenGL W32!\n")); if (!wglDeleteContext(attrib_ctx)) { mprintf(("Failed to delete render context!")); } return nullptr; } if (!gladLoadWGLLoader(gladWGLLoader, mfcView->getHDC())) { mprintf(("Failed to load WGL functions!\n")); wglMakeCurrent(nullptr, nullptr); if (!wglDeleteContext(temp_ctx)) { mprintf(("Failed to delete render context!")); } return nullptr; } return std::unique_ptr<os::OpenGLContext>(new MFCOpenGLContext(attrib_ctx)); }
std::unique_ptr<os::Viewport> MFCGraphicsOperations::createViewport(const os::ViewPortProperties& props) { int PixelFormat; PIXELFORMATDESCRIPTOR pfd_test; PIXELFORMATDESCRIPTOR GL_pfd; mprintf((" Initializing WGL...\n")); memset(&GL_pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); memset(&pfd_test, 0, sizeof(PIXELFORMATDESCRIPTOR)); GL_pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); GL_pfd.nVersion = 1; GL_pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; if (props.enable_opengl) { GL_pfd.dwFlags |= PFD_SUPPORT_OPENGL; } GL_pfd.iPixelType = PFD_TYPE_RGBA; GL_pfd.cColorBits = (BYTE)(props.pixel_format.red_size + props.pixel_format.green_size + props.pixel_format.blue_size + props.pixel_format.alpha_size); GL_pfd.cRedBits = (BYTE)(props.pixel_format.red_size); GL_pfd.cGreenBits = (BYTE)(props.pixel_format.green_size); GL_pfd.cBlueBits = (BYTE)(props.pixel_format.blue_size); GL_pfd.cAlphaBits = (BYTE)(props.pixel_format.alpha_size); GL_pfd.cDepthBits = (BYTE)(props.pixel_format.depth_size); GL_pfd.cStencilBits = (BYTE)(props.pixel_format.stencil_size); Assert(_windowHandle != NULL); auto device_context = GetDC(_windowHandle); if (!device_context) { mprintf(("Unable to get device context for OpenGL W32!\n")); return nullptr; } PixelFormat = ChoosePixelFormat(device_context, &GL_pfd); if (!PixelFormat) { mprintf(("Unable to choose pixel format for OpenGL W32!\n")); ReleaseDC(_windowHandle, device_context); return nullptr; } else { DescribePixelFormat(device_context, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd_test); } if (!SetPixelFormat(device_context, PixelFormat, &GL_pfd)) { mprintf(("Unable to set pixel format for OpenGL W32!\n")); ReleaseDC(_windowHandle, device_context); return nullptr; } mprintf((" Requested SDL Video values = R: %d, G: %d, B: %d, depth: %d, stencil: %d\n", props.pixel_format.red_size, props.pixel_format.green_size, props.pixel_format.blue_size, props.pixel_format.depth_size, props.pixel_format.stencil_size)); return std::unique_ptr<os::Viewport>(new MFCViewport(_windowHandle, device_context)); }
int main(int argc, char **argv) { int c; int argco = argc; char **argvo = argv; fitness_type = FITNESS_MEAN_LIGHTSENSOR; int run_type = STANDARD_RUN; pid_t pid = getpid(); random_seed = (long) time(NULL) ^ pid; save_prefix = "."; quiet = 0; int force = 0; while ((c = getopt (argc, argv, "DT:F:s:fqM:d:R:")) != -1) switch (c) { case 'D': run_type = DEBUG_RUN; break; case 'T': run_type = atoi(optarg); break; case 'F': fitness_type = atoi(optarg); break; case 's': random_seed = atol(optarg); break; case 'f': force = 1; break; case 'q': quiet = 1; break; case 'M': mut_prob = atof(optarg); break; case 'd': save_prefix = optarg; break; case 'R': reset_freq = atoi(optarg); break; case '?': break; default: abort (); } // next argument at argv[optind] argc -= (optind - 1); argv += (optind - 1); srand48(random_seed); if (! quiet) printf("alps-like: Started!\n"); if (run_type == DEBUG_RUN) { goal_fitness = 0.9; } else if (run_type == EASY_RUN) { goal_fitness = 0.8; } if (argc != 4) { fprintf(stderr, "usage: alps-like [-fDq] [-M mutP] [-R resetF] [-T run-type] [-F fitness-type] [-d save-dir] <experiment-name> <task-index> <lobotomise> \n"); fprintf(stderr, "experiment names: An, Bn, Ap, Bp, Ao, Bo\n"); return 2; } //register_signal_handlers(); sim_init(); exp_name = argv[1]; task_index = atoi(argv[2]) - 1; lobotomise = (atoi(argv[3]) == 1); //if (mkdir(save_prefix, 0777)) { char cmd[255]; sprintf(cmd, "mkdir -p %s", save_prefix); if (system(cmd)) { fprintf(stderr, "error: cannot create directory '%s'.\n", save_prefix); return 4; } char filename[255]; sprintf(filename, "%s/results.m", save_prefix); mfile = fopen(filename, "w"); sprintf(filename, "%s/table.txt", save_prefix); table = fopen(filename, "w"); sprintf(filename, "%s/run_again.sh", save_prefix); FILE *run_again = fopen(filename, "w"); fprintf(run_again, "#!/bin/bash\n"); int i; mprintf(1, "commandLine -> \""); for (i = 0; i < argco; i++) { fprintf(run_again, "%s ", argvo[i]); mprintf(0, "%s ", argvo[i]); } mprintf(0, "\"\n"); fprintf(run_again, "\n"); fclose(run_again); mprintf(1, "directory -> \"%s\"\n", save_prefix); int err; err = experiment_phase_count(exp_name, &phase_count); if (err) { fprintf(stderr, "error: cannot get phase count for experiment '%s'.\n", exp_name); err = 1; goto finish; } sprintf(filename, "%s/eval.sh", save_prefix); script = fopen(filename, "w"); fprintf(script, "#!/bin/bash\n" "cd $(dirname $0)\n"); int steps; err = run_alps(&steps); if (err) { fprintf(stderr, "error: alps-like did not find an adequate solution.\n"); } mprintf(1, "{ success -> %s, exitCode -> %d }\n", err == 0 ? "True" : "False", err); sprintf(filename, "%s/FAILURE", save_prefix); if (err) { FILE* fail = fopen(filename, "w"); fprintf(fail, "%d\n", steps); fprintf(fail, "%d\n", err); fclose(fail); } else { unlink(filename); } sprintf(filename, "%s/SUCCESS", save_prefix); if (err) { unlink(filename); } else { FILE* suc = fopen(filename, "w"); fprintf(suc, "%d\n", steps); fclose(suc); } finish: if (! quiet) printf("alps-like: Finished. Logs: \n\n\t%s\n", save_prefix); sim_uninit(); if (mfile) fclose(mfile); if (table) fclose(table); if (script) fclose(script); return err; }
void CommandData::OutHelp() { #if !defined(GUI) && !defined(SILENT) OutTitle(); static MSGID Help[]={ #ifdef SFX_MODULE // Console SFX switches definition. MCHelpCmd,MSHelpCmdE,MSHelpCmdT,MSHelpCmdV #elif defined(UNRAR) // UnRAR switches definition. MUNRARTitle1,MRARTitle2,MCHelpCmd,MCHelpCmdE,MCHelpCmdL, MCHelpCmdP,MCHelpCmdT,MCHelpCmdV,MCHelpCmdX,MCHelpSw, MCHelpSwm,MCHelpSwAC,MCHelpSwAD,MCHelpSwAI,MCHelpSwAP, MCHelpSwCm,MCHelpSwCFGm,MCHelpSwCL,MCHelpSwCU, MCHelpSwDH,MCHelpSwEP,MCHelpSwEP3,MCHelpSwF,MCHelpSwIDP,MCHelpSwIERR, MCHelpSwINUL,MCHelpSwIOFF,MCHelpSwKB,MCHelpSwN,MCHelpSwNa,MCHelpSwNal, MCHelpSwO,MCHelpSwOC,MCHelpSwOR,MCHelpSwOW,MCHelpSwP, MCHelpSwPm,MCHelpSwR,MCHelpSwRI,MCHelpSwSL,MCHelpSwSM,MCHelpSwTA, MCHelpSwTB,MCHelpSwTN,MCHelpSwTO,MCHelpSwTS,MCHelpSwU,MCHelpSwVUnr, MCHelpSwVER,MCHelpSwVP,MCHelpSwX,MCHelpSwXa,MCHelpSwXal,MCHelpSwY #else #endif }; for (int I=0;I<sizeof(Help)/sizeof(Help[0]);I++) { #ifndef SFX_MODULE #ifdef DISABLEAUTODETECT if (Help[I]==MCHelpSwV) continue; #endif #ifndef _WIN_32 static MSGID Win32Only[]={ MCHelpSwIEML,MCHelpSwVD,MCHelpSwAO,MCHelpSwOS,MCHelpSwIOFF, MCHelpSwEP2,MCHelpSwOC,MCHelpSwDR,MCHelpSwRI }; bool Found=false; for (int J=0;J<sizeof(Win32Only)/sizeof(Win32Only[0]);J++) if (CmpMSGID(Help[I],Win32Only[J])) { Found=true; break; } if (Found) continue; #endif #if !defined(_UNIX) && !defined(_WIN_32) if (CmpMSGID(Help[I],MCHelpSwOW)) continue; #endif #if !defined(_WIN_32) && !defined(_EMX) if (CmpMSGID(Help[I],MCHelpSwAC)) continue; #endif #ifndef SAVE_LINKS if (CmpMSGID(Help[I],MCHelpSwOL)) continue; #endif #ifndef PACK_SMP if (CmpMSGID(Help[I],MCHelpSwMT)) continue; #endif #ifndef _BEOS if (CmpMSGID(Help[I],MCHelpSwEE)) { #if defined(_EMX) && !defined(_DJGPP) if (_osmode != OS2_MODE) continue; #else continue; #endif } #endif #endif mprintf(St(Help[I])); } mprintf("\n"); ErrHandler.Exit(USER_ERROR); #endif }
void * tbMaster (ProcessData * pData, WavesData * wData) { int MPI_return, foundproc, done = 0; /*currProc*/ MOATypeDimn i, k; long long receviedLongLong; char msg[MID_MESSAGE_SIZE]; MPI_Request request; MPI_Status status; TracebackData * tbData; tbData = NULL; if (initTBData(&tbData, pData->seqNum, pData->seqLen) != 0) { printf ("Failed to allocate memory for trace back structure. Exiting\n"); return NULL; } if (AlignmentType == Local) getmaxCellScore (pData, tbData); else { //tbData->maxCellScore = getLocalMaxCellScore(pData, wData, tbData, 0); pData->waveNo = wData->wavesTotal - 1; pData->partNo = wData->partsInWave[pData->waveNo]-1; tbData->maxCellScore = 0; if (getProcID(wData, pData->waveNo, pData->partNo) != myProcid) getPrevPartition (wData, &pData->waveNo, &pData->partNo); if (pData->partNo != -1) { if (restorePartitionCheckPoint(pData, wData, pData->waveNo, pData->partNo) != 0) { printf ("Error Retrieving partition file. Exitiing.\n"); return NULL; } for (k=0;k<pData->seqNum;k++) tbData->maxCellIndex[k] = pData->msaAlgn->indexes[pData->msaAlgn->elements_ub-1][k]; } else { printf ("Error Retrieving part No. Exitiing.\n"); return NULL; } tbData->currProc = 0; } //currProc = tbData->currProc; while (done == 0) { printf ("currProc = %d done = %d maxCellIndex { %lld", tbData->currProc, done, tbData->maxCellIndex[0]); for (k=1;k<tbData->seqNum;k++) printf (", %lld", tbData->maxCellIndex[k]); printf ("} in proc %d\n", tbData->currProc); /*send to processor containing the maxCellScore to trace back*/ if (tbData->currProc == 0) { /*Perform Partition trace back*/ tbData->pathParts ++; if (tbData->pathParts == 1) { tbData->aSeqLen = mmalloc (((MOATypeInd) sizeof *(tbData->aSeqLen))); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments Lengths. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } tbData->algnseq = mmalloc (((MOATypeInd) sizeof *(tbData->algnseq))); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } } else { tbData->aSeqLen = realloc (tbData->aSeqLen, ((MOATypeInd) tbData->pathParts) * ((MOATypeInd) sizeof *(tbData->aSeqLen))); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments Lengths. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } tbData->algnseq = realloc (tbData->algnseq, ((MOATypeInd) tbData->pathParts) * ((MOATypeInd) sizeof *(tbData->algnseq))); if (tbData->algnseq == NULL) { printf ("Failed to reallocate memory for %ld partial alignments. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } } tbData->algnseq[tbData->pathParts-1] = NULL; tbData->algnseq[tbData->pathParts-1] = mmalloc (((MOATypeInd) tbData->seqNum) * ((MOATypeInd) sizeof *(tbData->algnseq[tbData->pathParts-1]))); if (tbData->algnseq[tbData->pathParts-1] == NULL) { printf ("Failed to reallocate memory for %ld partial alignments sequences. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } tbData->aSeqLen[tbData->pathParts-1] = traceBack(pData, wData, tbData); sprintf(msg, "DMTB returned Local path of length %ld\n", tbData->aSeqLen[tbData->pathParts-1]); mprintf(3, msg, 1); } else { /*1. Send Tracing flag (done = 0) to the processor where the maximum score was found*/ MPI_return = MPI_Send (&done, 1, MPI_INT, tbData->currProc, 2, MOAMSA_COMM_WORLD); #ifndef NDEBUG sprintf(msg, "DMTB sent flag %d to proc %d first\n", done, tbData->currProc); mprintf(3, msg, 1); #endif /*2. send starting global index*/ MPI_return = MPI_Send (tbData->maxCellIndex, tbData->seqNum, MPI_LONG_LONG, tbData->currProc, 3, MOAMSA_COMM_WORLD); #ifndef NDEBUG sprintf(msg, "DMTB sent maxCellIndex to proc %d\n", tbData->currProc); mprintf(3, msg, 1); #endif tbData->pathParts ++; if (tbData->pathParts == 1) { tbData->aSeqLen = mmalloc (((MOATypeInd) sizeof *tbData->aSeqLen)); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments Lengths. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } tbData->algnseq = mmalloc (((MOATypeInd) sizeof *tbData->algnseq)); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } } else { tbData->aSeqLen = realloc (tbData->aSeqLen, ((MOATypeInd) tbData->pathParts) * ((MOATypeInd) sizeof *tbData->aSeqLen)); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments Lengths. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } tbData->algnseq = realloc (tbData->algnseq, ((MOATypeInd) tbData->pathParts) * ((MOATypeInd) sizeof *tbData->algnseq)); if (tbData->aSeqLen == NULL) { printf ("Failed to reallocate memory for %ld partial alignments. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } } tbData->algnseq[tbData->pathParts-1] = NULL; tbData->algnseq[tbData->pathParts-1] = mmalloc (((MOATypeInd) tbData->seqNum) * ((MOATypeInd) sizeof *(tbData->algnseq[tbData->pathParts-1]))); if (tbData->algnseq[tbData->pathParts-1] == NULL) { printf ("Failed to reallocate memory for %ld partial alignments sequences. Exiting.\n", tbData->pathParts); fflush (stdout); return NULL; } tbData->aSeqLen[tbData->pathParts-1] = 2; /*3. receive partital alignment length*/ MPI_return = MPI_Recv (&receviedLongLong, 1, MPI_LONG_LONG, tbData->currProc, 4, MOAMSA_COMM_WORLD, &status); tbData->aSeqLen[tbData->pathParts-1] = receviedLongLong; #ifndef NDEBUG printf("Master received length %ld MPI_return %d \n", tbData->aSeqLen[tbData->pathParts-1], MPI_return); fflush(stdout); sprintf(msg, "DMTB received Remote path of length %ld :", tbData->aSeqLen[tbData->pathParts-1]); mprintf(3, msg, 1); #endif /*4. receive the partital alignment itself*/ for (i=0;i<tbData->seqNum && tbData->aSeqLen[tbData->pathParts-1] > 0;i++) { tbData->algnseq[tbData->pathParts-1][i] = NULL; tbData->algnseq[tbData->pathParts-1][i] = mmalloc (((MOATypeInd) (tbData->aSeqLen[tbData->pathParts-1] +1)) * ((MOATypeInd) sizeof *(tbData->algnseq[tbData->pathParts-1][i] ))); if (tbData->algnseq[tbData->pathParts-1][i] == NULL) { printf ("Failed to reallocate memory for %ld partial alignments sequences %lld residues. Exiting.\n", tbData->pathParts, tbData->aSeqLen[tbData->pathParts-1]); fflush (stdout); return NULL; } MPI_return = MPI_Recv (tbData->algnseq[tbData->pathParts-1][i], tbData->aSeqLen[tbData->pathParts-1], MPI_CHAR, tbData->currProc, 5, MOAMSA_COMM_WORLD, &status); tbData->algnseq[tbData->pathParts-1][i][tbData->aSeqLen[tbData->pathParts-1]] = '\0'; #ifndef NDEBUG printf("Master received aligned seq for seq %lld MPI_return %d = %s\n", i, MPI_return, tbData->algnseq[tbData->pathParts-1][i]); fflush(stdout); sprintf(msg, " %s ", tbData->algnseq[tbData->pathParts-1][i]); mprintf(3, msg, 1); #endif } /*5. receive the last global index in this partial alignment*/ MPI_return = MPI_Recv (tbData->maxCellIndex, tbData->seqNum, MPI_LONG_LONG, tbData->currProc, 7, MOAMSA_COMM_WORLD, &status); #ifndef NDEBUG printf ("Master received MPI_return %d maxCellIndex { %lld", MPI_return, tbData->maxCellIndex[0]); for (i=1;i<tbData->seqNum;i++) printf (", %lld", tbData->maxCellIndex[i]); printf ("}\n"); fflush(stdout); #endif /*6. receive the next Processor where a next remote score was found from this partial alignment*/ MPI_return = MPI_Recv (&tbData->currProc, 1, MPI_INT, tbData->currProc, 8, MOAMSA_COMM_WORLD, &status); //tbData->currProc = currProc; #ifndef NDEBUG sprintf(msg, "DMTB received currProc %d, maxCellIndex {%lld", tbData->currProc, tbData->maxCellIndex[0]); for (k=1;k<tbData->seqNum;k++) sprintf(msg, "%s, %lld", msg, tbData->maxCellIndex[k]); sprintf(msg, "%s}\n", msg); mprintf(3, msg, 1); #endif } /*test if end of aligned sequence is zero to exit */ done = 2; for (k=0;k<tbData->seqNum;k++) if (tbData->maxCellIndex[k] != 0) done = 0; /* else, determine the next tracing Processor*/ if ((done == 0) && (tbData->currProc < 0)) { /*if other slave processes don't have this index, check the master*/ if (getPartitionDetails (pData, wData, &tbData->partIndex, tbData->maxCellIndex, &pData->waveNo, &pData->partNo, &tbData->currProc) == 0) { #ifndef NDEBUG sprintf(msg, "DMTB max cell {%lld", tbData->maxCellIndex[0]); for (k=1;k<tbData->seqNum;k++) sprintf (msg, "%s, %lld", msg, tbData->maxCellIndex[k]); sprintf (msg, "%s} in proc %d\n", msg, tbData->currProc); mprintf(3, msg, 1); #endif done = 0; } else /*other wise, end of tracing*/ done = 2; } } /* End While*/ /*send to all processes to exit tracing*/ done = 2; for (i=1;i<ClusterSize;i++) { MPI_return = MPI_Send (&done, 1, MPI_INT, i, 2, MOAMSA_COMM_WORLD); sprintf(msg, "DMTB sent flag %d to proc %ld\n", done, i); mprintf(3, msg, 1); } assemblePathParts (tbData); calcAlignmentSPScore(pData, tbData); outputAlignment(pData, tbData, 1); editAlignment (pData, tbData); calcAlignmentSPScore (pData, tbData); outputAlignment(pData, tbData, 1); outputFastaAlignment(pData, tbData); outputMSFAlignment(outputfilename, pData, tbData); if (tbData != NULL) freetbData(&tbData); return NULL; }
void convert_pilot_files() { size_t idx, j, i; size_t count, inf_count; int max_convert, num_converted = 0; SCP_vector<SCP_string> existing; SCP_vector<SCP_string> old_files; // get list of pilots which already exist (new or converted already) cf_get_file_list(existing, CF_TYPE_PLAYERS, "*.plr"); // get list of old pilots which may need converting, starting with inferno pilots Get_file_list_child = "inferno"; cf_get_file_list(old_files, CF_TYPE_SINGLE_PLAYERS, "*.pl2"); inf_count = old_files.size(); cf_get_file_list(old_files, CF_TYPE_SINGLE_PLAYERS, "*.pl2"); if ( old_files.empty() ) { return; } // rip out all files which already exist i = 0; count = old_files.size(); for (idx = 0; idx < existing.size(); idx++) { const char *fname = existing[idx].c_str(); for (j = 0; j < count; j++) { if ( !stricmp(fname, old_files[j].c_str()) ) { // NOTE: we just clear the name here to avoid the fragmentation // from resizing the vector old_files[j] = ""; ++i; } } } // don't convert enough pilots to exceed the pilot limit max_convert = MAX_PILOTS - (int)existing.size(); // if everything is already converted then bail // also bail if MAX_PILOTS (or more!) already exist if (i == count || max_convert <= 0) { return; } mprintf(("PILOT: Beginning pilot file conversion...\n")); // now proceed to convert all of the old files count = old_files.size(); for (idx = 0; idx < count; idx++) { if ( old_files[idx].empty() ) { continue; } pilotfile_convert *pcon = new pilotfile_convert; bool inferno = (idx < inf_count); if ( pcon->plr_convert(old_files[idx].c_str(), inferno) ) { SCP_vector<SCP_string> savefiles; SCP_string wildcard(old_files[idx]); wildcard.append("*.cs2"); if (inferno) { Get_file_list_child = "inferno"; } cf_get_file_list(savefiles, CF_TYPE_SINGLE_PLAYERS, wildcard.c_str()); for (j = 0; j < savefiles.size(); j++) { pcon->csg_convert(savefiles[j].c_str(), inferno); } ++num_converted; } delete pcon; if (num_converted >= max_convert) { break; } } mprintf(("PILOT: Pilot file conversion complete!\n")); }
int main (int argc, char * argv[]) { MPI_Group orig_group; pthread_t MasterThread, SlaveThread; MOATypeDimn seqNum; MOATypeShape * seqLen = NULL; char * * sequences = NULL, * * seqName = NULL, msg[MID_MESSAGE_SIZE]; long partitionSize; long ID1; int stype, MPI_return; /*char ufilename[SHORT_MESSAGE_SIZE];*/ int ret; ProcessData * pData; ScoringData * sData; WavesData * wData; MPI_Init (&argc, &argv); MPI_Comm_rank (MPI_COMM_WORLD, &myProcid); MPI_Comm_size (MPI_COMM_WORLD, &ClusterSize); MPI_Comm_group (MPI_COMM_WORLD, &orig_group); MPI_Comm_create(MPI_COMM_WORLD, orig_group, &MOAMSA_COMM_WORLD); TBFlag = 1; prevNow = NULL; prevNow = mmalloc ((MOATypeInd) sizeof *prevNow); currNow = NULL; //currNow = mmalloc ((MOATypeInd) sizeof *currNow); currNow = getTime(); if (currNow == NULL) { printf ("Could not read current time. Exiting.\n"); return -1; } ID1 = getpid(); printf("[%d]>PID = %ld Started at time (%d, %d, %d, %d)\n", myProcid, ID1, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec); /* 1. Process Arguments*/ processArguments(argc, argv, &seqNum, &sequences, &seqName, &seqLen, &stype, &partitionSize); /*strcpy (ufilename, outputfilename);*/ strcpy (outPrefix, "b"); /*sprintf (outputfilename, "mmtb%s", ufilename);*/ init_output(); sprintf (msg, "Program Arguments: debuglevel = %d maxAlignmentsNumber = %d Epsilons= %ld Alignment Type = %d stype %d outputfilename = %s partitionSize = %ld\n", pdebug, maxAlignmentsNumber, Epsilons, AlignmentType, stype, outputfilename, partitionSize); mprintf (1, msg, 1); /*2. Do the Master Tasks: Synchronize with Slaves to trace back*/ /* one path for now*/ ret = initProcessMemory(&pData, &sData, &wData, seqNum, seqLen, sequences, seqName, stype, partitionSize); if (ret != 0) { mprintf (1, " Could not initialize process memory\n", 1); ExitProcess (pData, sData, wData); return -1; } mprintf (1, "Initialized Slave data and will read checkpoint file\n", 1); /*3. Load Tensor Partitions Computed*/ ret = restoreCheckPoint (pData, wData); if (ret != 0) { printf (" Could not read Slave data from checkpoint file\n"); ExitProcess (pData, sData, wData); return -1; } if (pData->computedPartitions <= 0) { mprintf (1, " No Partitions read in this process\n", 1); /*ExitProcess (pData);*/ /*return -1;*/ } else { sprintf (msg, "read Slave data from checkpoint file partitions %ld last score in last partition is %ld sqm %ld sqlen0 %ld %ld %ld\n", pData->partitionsCount, pData->msaAlgn->elements[pData->msaAlgn->elements_ub - 1].val, pData->seqNum, pData->seqLen[0], pData->seqLen[1], pData->seqLen[2]); mprintf(3, msg, 1); } if (myProcid == 0) tbMaster(pData, wData); else /* do the slave tasks*/ tbSlave(pData, wData); if (myProcid == 0) { /* Getting Process Resources Usage ===================== */ struct rusage usageRec; double utime, stime; ret = getrusage(RUSAGE_SELF, &usageRec); if (ret == 0) { //printf ("[%d]Resources Usage: UTime %ld, STime %ld, Mem %ld, Virt %ld\n", myProcid, usageRec.ru_utime.tv_sec, usageRec.ru_stime.tv_sec, usageRec.ru_maxrss, usageRec.ru_ixrss); utime = (double) usageRec.ru_utime.tv_sec + 1.e-6 * (double) usageRec.ru_utime.tv_usec; stime = (double) usageRec.ru_stime.tv_sec + 1.e-6 * (double) usageRec.ru_stime.tv_usec; //printf ("[%d]Resources Usage: UTime %f, STime %f\n", myProcid, utime, stime); } else printf ("[%d]Failed to retrieve Process Resources Usage, errno %d\n", myProcid, errno); //struct mallinfo info; //info = mallinfo(); //printf("[%d] STime\tUTime\theap\tMemory\t\n",myProcid); //printf("[%d] %f\t%f\t%d\t%d\n", myProcid, stime, utime, info.arena, info.usmblks + info.uordblks); printf("[%d] STime\tUTime\n",myProcid); printf("[%d] %f\t%f\n", myProcid, stime, utime); currNow = getTime(); printf("[%d]>Finalized at time (%d, %d, %d, %d)\n", myProcid, currNow->tm_yday, currNow->tm_hour, currNow->tm_min, currNow->tm_sec); } ExitProcess (pData, sData, wData); return 0; }
// Exec_PermuteDihedrals::RandomizeAngles() void Exec_PermuteDihedrals::RandomizeAngles(Frame& currentFrame, Topology const& topIn) { Matrix_3x3 rotationMatrix; # ifdef DEBUG_PERMUTEDIHEDRALS // DEBUG int debugframenum=0; Trajout_Single DebugTraj; DebugTraj.PrepareTrajWrite("debugtraj.nc",ArgList(),(Topology*)&topIn, topIn.ParmCoordInfo(), topIn.Nframes(), TrajectoryFile::AMBERNETCDF); DebugTraj.WriteSingle(debugframenum++,currentFrame); # endif int next_resnum; int bestLoop = 0; int number_of_rotations = 0; // Set max number of rotations to try. int max_rotations = (int)BB_dihedrals_.size(); max_rotations *= max_factor_; // Loop over all dihedrals std::vector<PermuteDihedralsType>::const_iterator next_dih = BB_dihedrals_.begin(); next_dih++; for (std::vector<PermuteDihedralsType>::const_iterator dih = BB_dihedrals_.begin(); dih != BB_dihedrals_.end(); ++dih, ++next_dih) { ++number_of_rotations; // Get the residue atom of the next dihedral. Residues up to and // including this residue will be checked for bad clashes if (next_dih != BB_dihedrals_.end()) next_resnum = next_dih->resnum; else next_resnum = dih->resnum - 1; // Set axis of rotation Vec3 axisOfRotation = currentFrame.SetAxisOfRotation(dih->atom1, dih->atom2); // Generate random value to rotate by in radians // Guaranteed to rotate by at least 1 degree. // NOTE: could potentially rotate 360 - prevent? // FIXME: Just use 2PI and rn_gen, get everything in radians double theta_in_degrees = ((int)(RN_.rn_gen()*100000) % 360) + 1; double theta_in_radians = theta_in_degrees * Constants::DEGRAD; // Calculate rotation matrix for random theta rotationMatrix.CalcRotationMatrix(axisOfRotation, theta_in_radians); int loop_count = 0; double clash = 0; double bestClash = 0; if (debug_>0) mprintf("DEBUG: Rotating dihedral %zu res %8i:\n", dih - BB_dihedrals_.begin(), dih->resnum+1); bool rotate_dihedral = true; while (rotate_dihedral) { if (debug_>0) { mprintf("\t%8i %12s %12s, +%.2lf degrees (%i).\n",dih->resnum+1, topIn.AtomMaskName(dih->atom1).c_str(), topIn.AtomMaskName(dih->atom2).c_str(), theta_in_degrees,loop_count); } // Rotate around axis currentFrame.Rotate(rotationMatrix, dih->Rmask); # ifdef DEBUG_PERMUTEDIHEDRALS // DEBUG DebugTraj.WriteSingle(debugframenum++,currentFrame); # endif // If we dont care about sterics exit here if (!check_for_clashes_) break; // Check resulting structure for issues int checkresidue; if (!checkAllResidues_) checkresidue = CheckResidue(currentFrame, topIn, *dih, next_resnum, clash); else checkresidue = CheckResidue(currentFrame, topIn, *dih, topIn.Nres(), clash); if (checkresidue==0) rotate_dihedral = false; else if (checkresidue==-1) { if (dih - BB_dihedrals_.begin() < 2) { mprinterr("Error: Cannot backtrack; initial structure already has clashes.\n"); number_of_rotations = max_rotations + 1; } else { dih--; // 0 dih--; // -1 next_dih = dih; next_dih++; if (debug_>0) mprintf("\tCannot resolve clash with further rotations, trying previous again.\n"); } break; } if (clash > bestClash) {bestClash = clash; bestLoop = loop_count;} //n_problems = CheckResidues( currentFrame, second_atom ); //if (n_problems > -1) { // mprintf("%i\tCheckResidues: %i problems.\n",frameNum,n_problems); // rotate_dihedral = false; //} else if (loop_count==0) { if (loop_count==0 && rotate_dihedral) { if (debug_>0) mprintf("\tTrying dihedral increments of +%i\n",increment_); // Instead of a new random dihedral, try increments theta_in_degrees = (double)increment_; theta_in_radians = theta_in_degrees * Constants::DEGRAD; // Calculate rotation matrix for new theta rotationMatrix.CalcRotationMatrix(axisOfRotation, theta_in_radians); } ++loop_count; if (loop_count == max_increment_) { if (debug_>0) mprintf("%i iterations! Best clash= %.3lf at %i\n",max_increment_, sqrt(bestClash),bestLoop); if (dih - BB_dihedrals_.begin() < backtrack_) { mprinterr("Error: Cannot backtrack; initial structure already has clashes.\n"); number_of_rotations = max_rotations + 1; } else { for (int bt = 0; bt < backtrack_; bt++) dih--; next_dih = dih; next_dih++; if (debug_>0) mprintf("\tCannot resolve clash with further rotations, trying previous %i again.\n", backtrack_ - 1); } break; // Calculate how much to rotate back in order to get to best clash /*int num_back = bestLoop - 359; theta_in_degrees = (double) num_back; theta_in_radians = theta_in_degrees * Constants::DEGRAD; // Calculate rotation matrix for theta calcRotationMatrix(rotationMatrix, axisOfRotation, theta_in_radians); // Rotate back to best clash frm.Frm().RotateAroundAxis(rotationMatrix, theta_in_radians, dih->Rmask); // DEBUG DebugTraj.WriteFrame(debugframenum++,currentParm,*currentFrame); // Sanity check CheckResidue(currentFrame, *dih, second_atom, &clash); rotate_dihedral=false;*/ //DebugTraj.EndTraj(); //return 1; } } // End dihedral rotation loop // Safety valve - number of defined dihedrals times * maxfactor if (number_of_rotations > max_rotations) { mprinterr("Error: # of rotations (%i) exceeds max rotations (%i), exiting.\n", number_of_rotations, max_rotations); //# ifdef DEBUG_PERMUTEDIHEDRALS // DebugTraj.EndTraj(); //# endif // Return gracefully for now break; //return 1; } } // End loop over dihedrals # ifdef DEBUG_PERMUTEDIHEDRALS DebugTraj.EndTraj(); mprintf("\tNumber of rotations %i, expected %u\n",number_of_rotations,BB_dihedrals_.size()); # endif }
void parse_mod_table(const char *filename) { // SCP_vector<SCP_string> lines; try { if (filename == NULL) read_file_text_from_default(defaults_get_file("game_settings.tbl")); else read_file_text(filename, CF_TYPE_TABLES); reset_parse(); // start parsing optional_string("#GAME SETTINGS"); if (optional_string("$Minimum version:") || optional_string("$Target Version:")) { Targetted_version = gameversion::parse_version(); mprintf(("Game Settings Table: Parsed target version of %s\n", gameversion::format_version(Targetted_version).c_str())); if (!gameversion::check_at_least(Targetted_version)) { Error(LOCATION, "This modification needs at least version %s of FreeSpace Open. However, the current is only %s!", gameversion::format_version(Targetted_version).c_str(), gameversion::format_version(gameversion::get_executable_version()).c_str()); } } if (optional_string("$Window title:")) { stuff_string(Window_title, F_NAME); } if (optional_string("$Window icon:")) { stuff_string(Window_icon_path, F_NAME); } if (optional_string("$Unicode mode:")) { stuff_boolean(&Unicode_text_mode); mprintf(("Game settings table: Unicode mode: %s\n", Unicode_text_mode ? "yes" : "no")); } optional_string("#CAMPAIGN SETTINGS"); if (optional_string("$Default Campaign File Name:")) { char temp[MAX_FILENAME_LEN]; stuff_string(temp, F_NAME, MAX_FILENAME_LEN); // remove extension? if (drop_extension(temp)) { mprintf(("Game Settings Table: Removed extension on default campaign file name %s\n", temp)); } // check length size_t maxlen = (MAX_FILENAME_LEN - 4); auto len = strlen(temp); if (len > maxlen) { error_display(0, "Token too long: [%s]. Length = " SIZE_T_ARG ". Max is " SIZE_T_ARG ".", temp, len, maxlen); temp[maxlen] = 0; } strcpy_s(Default_campaign_file_name, temp); } if (optional_string("#Ignored Campaign File Names")) { SCP_string campaign_name; while (optional_string("$Campaign File Name:")) { stuff_string(campaign_name, F_NAME); // remove extension? if (drop_extension(campaign_name)) { mprintf(("Game Settings Table: Removed extension on ignored campaign file name %s\n", campaign_name.c_str())); } // we want case-insensitive matching, so make this lowercase std::transform(campaign_name.begin(), campaign_name.end(), campaign_name.begin(), ::tolower); Ignored_campaigns.push_back(campaign_name); } } // Note: this feature does not ignore missions that are contained in campaigns if (optional_string("#Ignored Mission File Names")) { SCP_string mission_name; while (optional_string("$Mission File Name:")) { stuff_string(mission_name, F_NAME); // remove extension? if (drop_extension(mission_name)) { mprintf(("Game Settings Table: Removed extension on ignored mission file name %s\n", mission_name.c_str())); } // we want case-insensitive matching, so make this lowercase std::transform(mission_name.begin(), mission_name.end(), mission_name.begin(), ::tolower); Ignored_missions.push_back(mission_name); } } if (optional_string("$Red-alert applies to delayed ships:")) { stuff_boolean(&Red_alert_applies_to_delayed_ships); if (Red_alert_applies_to_delayed_ships) { mprintf(("Game Settings Table: Red-alert stats will be loaded for ships that arrive later in missions\n")); } else { mprintf(("Game Settings Table: Red-alert stats will NOT be loaded for ships that arrive later in missions (this is retail behavior)\n")); } } optional_string("#HUD SETTINGS"); // how long should the game wait before displaying a directive? if (optional_string("$Directive Wait Time:")) { stuff_int(&Directive_wait_time); } if (optional_string("$Cutscene camera displays HUD:")) { stuff_boolean(&Cutscene_camera_displays_hud); } // compatibility if (optional_string("$Cutscene camera disables HUD:")) { mprintf(("Game Settings Table: \"$$Cutscene camera disables HUD\" is deprecated in favor of \"$Cutscene camera displays HUD\"\n")); bool temp; stuff_boolean(&temp); Cutscene_camera_displays_hud = !temp; } if (optional_string("$Full color head animations:")) { stuff_boolean(&Full_color_head_anis); } // compatibility if (optional_string("$Color head animations with hud colors:")) { mprintf(("Game Settings Table: \"$Color head animations with hud colors\" is deprecated in favor of \"$Full color head animations\"\n")); bool temp; stuff_boolean(&temp); Full_color_head_anis = !temp; } optional_string("#SEXP SETTINGS"); if (optional_string("$Loop SEXPs Then Arguments:")) { stuff_boolean(&True_loop_argument_sexps); if (True_loop_argument_sexps) { mprintf(("Game Settings Table: Using Reversed Loops For SEXP Arguments\n")); } else { mprintf(("Game Settings Table: Using Standard Loops For SEXP Arguments\n")); } } if (optional_string("$Use Alternate Chaining Behavior:")) { stuff_boolean(&Alternate_chaining_behavior); if (Alternate_chaining_behavior) { mprintf(("Game Settings Table: Using alternate event chaining behavior\n")); } else { mprintf(("Game Settings Table: Using standard event chaining behavior\n")); } } optional_string("#GRAPHICS SETTINGS"); if (optional_string("$Enable External Shaders:")) { stuff_boolean(&Enable_external_shaders); if (Enable_external_shaders) mprintf(("Game Settings Table: External shaders are enabled\n")); else mprintf(("Game Settings Table: External shaders are DISABLED\n")); } if (optional_string("$Default Detail Level:")) { int detail_level; stuff_int(&detail_level); mprintf(("Game Settings Table: Setting default detail level to %i of %i-%i\n", detail_level, 0, NUM_DEFAULT_DETAIL_LEVELS - 1)); if (detail_level < 0 || detail_level > NUM_DEFAULT_DETAIL_LEVELS - 1) { error_display(0, "Invalid detail level: %i, setting to %i", detail_level, Default_detail_level); } else { Default_detail_level = detail_level; } } if (optional_string("$Briefing Window FOV:")) { float fov; stuff_float(&fov); mprintf(("Game Settings Table: Setting briefing window FOV from %f to %f\n", Briefing_window_FOV, fov)); Briefing_window_FOV = fov; } if (optional_string("$Generic Pain Flash Factor:")) { stuff_float(&Generic_pain_flash_factor); if (Generic_pain_flash_factor != 1.0f) mprintf(("Game Settings Table: Setting generic pain flash factor to %.2f\n", Generic_pain_flash_factor)); } if (optional_string("$Shield Pain Flash Factor:")) { stuff_float(&Shield_pain_flash_factor); if (Shield_pain_flash_factor != 0.0f) mprintf(("Game Settings Table: Setting shield pain flash factor to %.2f\n", Shield_pain_flash_factor)); } if (optional_string("$BMPMAN Slot Limit:")) { int tmp; stuff_int(&tmp); mprintf(("Game Settings Table: $BMPMAN Slot Limit is deprecated and should be removed. It is not needed anymore.\n")); } optional_string("#NETWORK SETTINGS"); if (optional_string("$FS2NetD port:")) { stuff_int(&FS2NetD_port); if (FS2NetD_port) mprintf(("Game Settings Table: FS2NetD connecting to port %i\n", FS2NetD_port)); } optional_string("#SOUND SETTINGS"); if (optional_string("$Default Sound Volume:")) { stuff_float(&Master_sound_volume); } if (optional_string("$Default Music Volume:")) { stuff_float(&Master_event_music_volume); } if (optional_string("$Default Voice Volume:")) { stuff_float(&Master_voice_volume); } optional_string("#FRED SETTINGS"); if (optional_string("$Disable Hard Coded Message Head Ani Files:")) { stuff_boolean(&Disable_hc_message_ani); if (Disable_hc_message_ani) { mprintf(("Game Settings Table: FRED - Disabling Hard Coded Message Ani Files\n")); } else { mprintf(("Game Settings Table: FRED - Using Hard Coded Message Ani Files\n")); } } if (optional_string("$Enable scripting in FRED:")) { stuff_boolean(&Enable_scripts_in_fred); if (Enable_scripts_in_fred) { mprintf(("Game Settings Table: FRED - Scripts will be executed when running FRED.\n")); } else { mprintf(("Game Settings Table: FRED - Scripts will not be executed when running FRED.\n")); } } optional_string("#OTHER SETTINGS"); if (optional_string("$Fixed Turret Collisions:")) { stuff_boolean(&Fixed_turret_collisions); } if (optional_string("$Damage Impacted Subsystem First:")) { stuff_boolean(&Damage_impacted_subsystem_first); } if (optional_string("$Default ship select effect:")) { char effect[NAME_LENGTH]; stuff_string(effect, F_NAME, NAME_LENGTH); if (!stricmp(effect, "FS2")) Default_ship_select_effect = 2; else if (!stricmp(effect, "FS1")) Default_ship_select_effect = 1; else if (!stricmp(effect, "off")) Default_ship_select_effect = 0; } if (optional_string("$Default weapon select effect:")) { char effect[NAME_LENGTH]; stuff_string(effect, F_NAME, NAME_LENGTH); if (!stricmp(effect, "FS2")) Default_weapon_select_effect = 2; else if (!stricmp(effect, "FS1")) Default_weapon_select_effect = 1; else if (!stricmp(effect, "off")) Default_weapon_select_effect = 0; } if (optional_string("$Weapons inherit parent collision group:")) { stuff_boolean(&Weapons_inherit_parent_collision_group); if (Weapons_inherit_parent_collision_group) mprintf(("Game Settings Table: Weapons inherit parent collision group\n")); } if (optional_string("$Flight controls follow eyepoint orientation:")) { stuff_boolean(&Flight_controls_follow_eyepoint_orientation); if (Flight_controls_follow_eyepoint_orientation) mprintf(("Game Settings Table: Flight controls follow eyepoint orientation\n")); } if (optional_string("$Beams Use Damage Factors:")) { stuff_boolean(&Beams_use_damage_factors); if (Beams_use_damage_factors) { mprintf(("Game Settings Table: Beams will use Damage Factors\n")); } else { mprintf(("Game Settings Table: Beams will ignore Damage Factors (retail behavior)\n")); } } if (optional_string("$Default fiction viewer UI:")) { char ui_name[NAME_LENGTH]; stuff_string(ui_name, F_NAME, NAME_LENGTH); if (!stricmp(ui_name, "auto")) Default_fiction_viewer_ui = -1; else { int ui_index = fiction_viewer_ui_name_to_index(ui_name); if (ui_index >= 0) Default_fiction_viewer_ui = ui_index; else error_display(0, "Unrecognized fiction viewer UI: %s", ui_name); } } if (optional_string("$Movie subtitle font:")) { // Fonts have not been parsed at this point so we can't validate the font name here stuff_string(Movie_subtitle_font, F_NAME); } if (optional_string("$Disable built-in translations:")) { stuff_boolean(&Disable_built_in_translations); } if (optional_string("$Weapon shockwave damage respects huge ship flags:")) { stuff_boolean(&Weapon_shockwaves_respect_huge); } if (optional_string("$Enable external default scripts:")) { stuff_boolean(&Enable_external_default_scripts); if (Enable_external_default_scripts) { mprintf(("Game Settings Table: Enabled external default scripts.\n")); } else { mprintf(("Game Settings Table: Disabled external default scripts.\n")); } } required_string("#END"); } catch (const parse::ParseException& e) { mprintf(("TABLES: Unable to parse '%s'! Error message = %s.\n", (filename) ? filename : "<default game_settings.tbl>", e.what())); return; } }
void HudGaugeReticle::getFirepointStatus() { //First, get the player ship ship_info* sip; ship* shipp; polymodel* pm; Assert(Objects[Player->objnum].type == OBJ_SHIP); if (Objects[Player->objnum].type == OBJ_SHIP) { shipp = &Ships[Objects[Player->objnum].instance]; sip = &Ship_info[shipp->ship_info_index]; //Get the player eyepoint pm = model_get(sip->model_num); if (pm->n_view_positions == 0) { mprintf(("Model %s does not have a defined eyepoint. Firepoint display could not be generated\n", pm->filename)); } else { if (pm->n_guns > 0) { eye eyepoint = pm->view_positions[shipp->current_viewpoint]; vec2d ep = { eyepoint.pnt.xyz.x, eyepoint.pnt.xyz.y }; for (int i = 0; i < pm->n_guns; i++) { int bankactive = 0; ship_weapon *swp = &shipp->weapons; if (!timestamp_elapsed(shipp->weapons.next_primary_fire_stamp[i])) bankactive = 1; else if (timestamp_elapsed(shipp->weapons.primary_animation_done_time[i])) bankactive = 1; else if (i == shipp->weapons.current_primary_bank || shipp->flags[Ship::Ship_Flags::Primary_linked]) bankactive = 2; int num_slots = pm->gun_banks[i].num_slots; for (int j = 0; j < num_slots; j++) { int fpactive = bankactive; if (sip->flags[Ship::Info_Flags::Dyn_primary_linking]) { // If this firepoint is not among the next shot(s) to be fired, dim it one step if ( !( (j >= (shipp->last_fired_point[i]+1) % num_slots) && (j <= (shipp->last_fired_point[i]+swp->primary_bank_slot_count[i]) % num_slots) ) ) { fpactive--; } } else if (Weapon_info[swp->primary_bank_weapons[i]].wi_flags2 & WIF2_CYCLE) { // If this firepoint is not the next one to be fired, dim it one step if (j != (shipp->last_fired_point[i]+1) % num_slots) { fpactive--; } } vec3d fpfromeye; matrix eye_orient, player_transpose; vm_copy_transpose(&player_transpose, &Objects[Player->objnum].orient); vm_matrix_x_matrix(&eye_orient, &player_transpose, &Eye_matrix); vm_vec_rotate(&fpfromeye, &pm->gun_banks[i].pnt[j], &eye_orient); firepoint tmp = { { fpfromeye.xyz.x - ep.x, ep.y - fpfromeye.xyz.y }, fpactive }; fp.push_back(tmp); } } } } } }
// Analysis_RemLog::Analyze() Analysis::RetType Analysis_RemLog::Analyze() { if (remlog_->Size() < 1) { mprinterr("Error: No replicas in remlog data '%s'\n", remlog_->legend()); return Analysis::ERR; } int Ndims = remlog_->DimTypes().Ndims(); mprintf("\t'%s' %i replicas, %i exchanges, %i dims.\n", remlog_->legend(), remlog_->Size(), remlog_->NumExchange(), Ndims); // Set up arrays for tracking replica stats. std::vector<RepStats> DimStats; std::vector<TripStats> DimTrips; for (int i = 0; i != Ndims; i++) { DimStats.push_back( RepStats(remlog_->Size()) ); if (calculateStats_) DimTrips.push_back( TripStats(remlog_->Size()) ); } std::vector< std::vector<int> > replicaFrac; if (calculateStats_) { replicaFrac.resize( remlog_->Size() ); // [replica][crdidx] for (std::vector< std::vector<int> >::iterator it = replicaFrac.begin(); it != replicaFrac.end(); ++it) it->resize( remlog_->Size(), 0 ); } // Variables for calculating replica lifetimes Analysis_Lifetime Lifetime; Array1D dsLifetime; std::vector< std::vector<DataSet_integer> > series; // 2D - repidx, crdidx if (calculateLifetimes_) { mprintf("\tData size used for lifetime analysis= %zu bytes.\n", remlog_->Size() * remlog_->Size() * remlog_->NumExchange() * sizeof(int)); series.resize( remlog_->Size() ); for (unsigned int i = 0; i < remlog_->Size(); i++) { series[i].resize( remlog_->Size() ); for (unsigned int j = 0; j < remlog_->Size(); j++) { series[i][j].Resize( remlog_->NumExchange() ); series[i][j].SetLegend("Rep"+integerToString(i+1)+",Crd"+integerToString(j+1)); dsLifetime.push_back( (DataSet_1D*)&(series[i][j]) ); } } if (Lifetime.ExternalSetup( dsLifetime, lifetimes_ ) == Analysis::ERR) { mprinterr("Error: Could not set up remlog lifetime analysis.\n"); return Analysis::ERR; } } DataSet_Mesh mesh; if ( calcRepFracSlope_ > 0 ) { mesh.CalculateMeshX( remlog_->Size(), 1, remlog_->Size() ); repFracSlope_->Printf("%-8s", "#Exchg"); for (int crdidx = 0; crdidx < (int)remlog_->Size(); crdidx++) repFracSlope_->Printf(" C%07i_slope C%07i_corel", crdidx + 1, crdidx + 1); repFracSlope_->Printf("\n"); } ProgressBar progress( remlog_->NumExchange() ); for (int frame = 0; frame < remlog_->NumExchange(); frame++) { progress.Update( frame ); for (int replica = 0; replica < (int)remlog_->Size(); replica++) { DataSet_RemLog::ReplicaFrame const& frm = remlog_->RepFrame( frame, replica ); int crdidx = frm.CoordsIdx() - 1; int repidx = frm.ReplicaIdx() - 1; int dim = frm.Dim(); // Exchange acceptance. // NOTE: Because currently the direction of the attempt is not always // known unless the attempt succeeds for certain remlog types, // the results will be skewed if dimension size is 2 since in that // case the left partner is the right partner. if (replica == 0) DimStats[dim].attempts_++; // Assume same # attempts for every rep in dim if (frm.Success()) { if (frm.PartnerIdx() - 1 == remlog_->ReplicaInfo()[replica][dim].RightID()) DimStats[dim].acceptUp_[replica]++; else // Assume down DimStats[dim].acceptDown_[replica]++; } if (mode_ == CRDIDX) { DataSet_integer& ds = static_cast<DataSet_integer&>( *(outputDsets_[repidx]) ); ds[frame] = frm.CoordsIdx(); } else if (mode_ == REPIDX) { DataSet_integer& ds = static_cast<DataSet_integer&>( *(outputDsets_[crdidx]) ); ds[frame] = frm.ReplicaIdx(); } if (calculateLifetimes_) series[repidx][crdidx][frame] = 1; if (calculateStats_) { TripStats& trip = static_cast<TripStats&>( DimTrips[dim] ); // Fraction spent at each replica replicaFrac[repidx][crdidx]++; // Replica round-trip calculation if (trip.status_[crdidx] == UNKNOWN) { if (remlog_->ReplicaInfo()[repidx][dim].Location() == DataSet_RemLog::BOTTOM) { trip.status_[crdidx] = HIT_BOTTOM; trip.bottom_[crdidx] = frame; } } else if (trip.status_[crdidx] == HIT_BOTTOM) { if (remlog_->ReplicaInfo()[repidx][dim].Location() == DataSet_RemLog::TOP) trip.status_[crdidx] = HIT_TOP; } else if (trip.status_[crdidx] == HIT_TOP) { if (remlog_->ReplicaInfo()[repidx][dim].Location() == DataSet_RemLog::BOTTOM) { int rtrip = frame - trip.bottom_[crdidx]; if (printIndividualTrips_) statsout_->Printf("[%i] CRDIDX %i took %i exchanges to travel" " up and down (exch %i to %i)\n", replica, crdidx+1, rtrip, trip.bottom_[crdidx]+1, frame+1); trip.roundTrip_[crdidx].AddElement( rtrip ); trip.status_[crdidx] = HIT_BOTTOM; trip.bottom_[crdidx] = frame; } } } } // END loop over replicas if (calcRepFracSlope_ > 0 && frame > 0 && (frame % calcRepFracSlope_) == 0) { repFracSlope_->Printf("%8i", frame+1); for (int crdidx = 0; crdidx < (int)remlog_->Size(); crdidx++) { for (int replica = 0; replica < (int)remlog_->Size(); replica++) mesh.SetY(replica, (double)replicaFrac[replica][crdidx] / (double)frame); double slope, intercept, correl; mesh.LinearRegression(slope, intercept, correl, 0); repFracSlope_->Printf(" %14.7g %14.7g", slope * 100.0, correl); //frame+1, crdidx, slope * 100.0, intercept * 100.0, correl } repFracSlope_->Printf("\n"); } } // END loop over exchanges // Exchange acceptance calc. for (int dim = 0; dim != Ndims; dim++) { // Assume number of exchange attempts is actually /2 since in Amber // attempts alternate up/down. acceptout_->Printf("DIMENSION %i\n", dim+1); if (debug_ > 0) { for (int replica = 0; replica != (int)remlog_->Size(); replica++) mprintf("Rep %i attempts %i up %i down %i\n", replica, DimStats[dim].attempts_, DimStats[dim].acceptUp_[replica], DimStats[dim].acceptDown_[replica]); } acceptout_->Printf("%-8s %8s %8s\n", "#Replica", "%UP", "%DOWN"); double exchangeAttempts = (double)DimStats[dim].attempts_ / 2.0; for (int replica = 0; replica != (int)remlog_->Size(); replica++) acceptout_->Printf("%8i %8.3f %8.3f\n", replica+1, ((double)DimStats[dim].acceptUp_[replica] / exchangeAttempts) * 100.0, ((double)DimStats[dim].acceptDown_[replica] / exchangeAttempts) * 100.0); } if (calculateStats_) { statsout_->Printf("# %i replicas, %i exchanges.\n", remlog_->Size(), remlog_->NumExchange()); for (int dim = 0; dim != Ndims; dim++) { if (Ndims > 1) statsout_->Printf("#Dim%i Round-trip stats:\n", dim+1); else statsout_->Printf("#Round-trip stats:\n"); statsout_->Printf("#%-8s %8s %12s %12s %12s %12s\n", "CRDIDX", "RndTrips", "AvgExch.", "SD_Exch.", "Min", "Max"); unsigned int idx = 1; for (DSI_array::const_iterator rt = DimTrips[dim].roundTrip_.begin(); rt != DimTrips[dim].roundTrip_.end(); ++rt) { double stdev = 0.0; double avg = rt->Avg( stdev ); statsout_->Printf("%-8u %8i %12.4f %12.4f %12.0f %12.0f\n", idx++, rt->Size(), avg, stdev, rt->Min(), rt->Max()); } } reptime_->Printf("#Percent time spent at each replica:\n%-8s", "#Replica"); for (int crd = 0; crd < (int)remlog_->Size(); crd++) reptime_->Printf(" CRD_%04i", crd + 1); reptime_->Printf("\n"); double dframes = (double)remlog_->NumExchange(); for (int replica = 0; replica < (int)remlog_->Size(); replica++) { reptime_->Printf("%8i", replica+1); for (int crd = 0; crd < (int)remlog_->Size(); crd++) reptime_->Printf(" %8.3f", ((double)replicaFrac[replica][crd] / dframes) * 100.0); reptime_->Printf("\n"); } } if (calculateLifetimes_) { mprintf("\tCalculating remlog lifetimes:\n"); Lifetime.Analyze(); } return Analysis::OK; }
static void fsmid_cache(const char *dpath, int ddirlen) { FILE *fi; /* * Already cached */ if ( FSMIDDCache && ddirlen == FSMIDDCacheDirLen && strncmp(dpath, FSMIDDCache, ddirlen) == 0 ) { return; } /* * Different cache, flush old cache */ if (FSMIDDCache != NULL) fsmid_flush(); /* * Create new cache */ FSMIDDCacheDirLen = ddirlen; FSMIDDCache = mprintf("%*.*s%s", ddirlen, ddirlen, dpath, FSMIDCacheFile); if ((fi = fopen(FSMIDDCache, "r")) != NULL) { FSMIDNode **pnode = &FSMIDBase; int c; c = fgetc(fi); while (c != EOF) { FSMIDNode *node = *pnode = malloc(sizeof(FSMIDNode)); char *s; int nlen; nlen = 0; if (pnode == NULL || node == NULL) fatal("out of memory"); bzero(node, sizeof(FSMIDNode)); node->fid_Code = strtoull(fextract(fi, -1, &c, ' '), NULL, 16); node->fid_Accessed = 1; if ((s = fextract(fi, -1, &c, ' ')) != NULL) { nlen = strtol(s, NULL, 0); free(s); } /* * extracting fid_Name - name may contain embedded control * characters. */ CountSourceReadBytes += nlen+1; node->fid_Name = fextract(fi, nlen, &c, EOF); if (c != '\n') { fprintf(stderr, "Error parsing FSMID Cache: %s (%c)\n", FSMIDDCache, c); while (c != EOF && c != '\n') c = fgetc(fi); } if (c != EOF) c = fgetc(fi); pnode = &node->fid_Next; } fclose(fi); } }
// Analysis_RemLog::Setup() Analysis::RetType Analysis_RemLog::Setup(ArgList& analyzeArgs, AnalysisSetup& setup, int debugIn) { debug_ = debugIn; // Get remlog dataset std::string remlogName = analyzeArgs.GetStringNext(); if (remlogName.empty()) { mprinterr("Error: no remlog data set or file name specified.\n"); return Analysis::ERR; } // Check if data set exists remlog_ = (DataSet_RemLog*)setup.DSL().FindSetOfType( remlogName, DataSet::REMLOG ); if (remlog_ == 0) { mprinterr("Error: remlog data with name %s not found.\n", remlogName.c_str()); return Analysis::ERR; } if (remlog_->Size() < 1 || remlog_->NumExchange() < 1) { mprinterr("Error: remlog data set appears to be empty.\n"); return Analysis::ERR; } acceptout_ = setup.DFL().AddCpptrajFile( analyzeArgs.GetStringKey("acceptout"), "replica acceptance", DataFileList::TEXT, true ); if (acceptout_ == 0) return Analysis::ERR; lifetimes_ = setup.DFL().AddCpptrajFile( analyzeArgs.GetStringKey("lifetime"), "remlog lifetimes" ); calculateLifetimes_ = (lifetimes_ != 0); calculateStats_ = analyzeArgs.hasKey("stats"); if (calculateStats_) { statsout_ = setup.DFL().AddCpptrajFile( analyzeArgs.GetStringKey("statsout"), "remlog stats", DataFileList::TEXT, true ); reptime_ = setup.DFL().AddCpptrajFile( analyzeArgs.GetStringKey("reptime"), "replica times", DataFileList::TEXT, true ); if (statsout_ == 0 || reptime_ == 0) return Analysis::ERR; } calcRepFracSlope_ = analyzeArgs.getKeyInt("reptimeslope", 0); std::string rfs_name = analyzeArgs.GetStringKey("reptimeslopeout"); if (!calculateStats_) { calcRepFracSlope_ = 0; rfs_name.clear(); } if ( (calcRepFracSlope_ > 0) != (!rfs_name.empty()) ) { mprinterr("Error: Both reptimeslope and reptimeslopeout must be specified.\n"); return Analysis::ERR; } repFracSlope_ = setup.DFL().AddCpptrajFile( rfs_name, "replica fraction slope" ); printIndividualTrips_ = analyzeArgs.hasKey("printtrips"); // Get mode if (analyzeArgs.hasKey("crdidx")) mode_ = CRDIDX; else if (analyzeArgs.hasKey("repidx")) mode_ = REPIDX; else mode_ = NONE; const char* def_name = 0; const char* yaxis = 0; if (mode_ == CRDIDX) { def_name = "repidx"; yaxis = "ylabel CrdIdx"; } else if (mode_ == REPIDX) { def_name = "crdidx"; yaxis = "ylabel RepIdx"; } // Set up an output set for each replica DataFile* dfout = 0; if (mode_ != NONE) { // Get output filename std::string outname = analyzeArgs.GetStringKey("out"); if (!outname.empty()) { dfout = setup.DFL().AddDataFile( outname, analyzeArgs ); if (dfout == 0 ) return Analysis::ERR; if (yaxis != 0 ) dfout->ProcessArgs(yaxis); } std::string dsname = analyzeArgs.GetStringKey("name"); if (dsname.empty()) dsname = setup.DSL().GenerateDefaultName(def_name); MetaData md(dsname); for (int i = 0; i < (int)remlog_->Size(); i++) { md.SetIdx(i+1); DataSet_integer* ds = (DataSet_integer*)setup.DSL().AddSet(DataSet::INTEGER, md); if (ds == 0) return Analysis::ERR; outputDsets_.push_back( (DataSet*)ds ); if (dfout != 0) dfout->AddDataSet( (DataSet*)ds ); ds->Resize( remlog_->NumExchange() ); } } mprintf(" REMLOG: %s, %i replicas, %i exchanges\n", remlog_->legend(), remlog_->Size(), remlog_->NumExchange()); if (mode_ == CRDIDX) mprintf("\tGetting coordinate index vs exchange.\n"); else if (mode_ == REPIDX) mprintf("\tGetting replica index vs exchange.\n"); if (mode_ != NONE && dfout != 0) mprintf("\tOutput is to %s\n", dfout->DataFilename().base()); if (calculateStats_) { mprintf("\tGetting replica exchange stats, output to %s\n", statsout_->Filename().full()); if (printIndividualTrips_) mprintf("\tIndividual round trips will be printed.\n"); mprintf("\tWriting time spent at each replica to %s\n", reptime_->Filename().full()); } if (calculateLifetimes_) mprintf("\tThe lifetime of each crd at each replica will be calculated.\n"); if (acceptout_ != 0) mprintf("\tOverall exchange acceptance % will be written to %s\n", acceptout_->Filename().full()); return Analysis::OK; }
void script_parse_table(const char *filename) { script_state *st = &Script_system; try { read_file_text(filename, CF_TYPE_TABLES); reset_parse(); if (optional_string("#Global Hooks")) { //int num = 42; //Script_system.SetHookVar("Version", 'i', &num); if (optional_string("$Global:")) { st->ParseChunk(&Script_globalhook, "Global"); } if (optional_string("$Splash:")) { st->ParseChunk(&Script_splashhook, "Splash"); } if (optional_string("$GameInit:")) { st->ParseChunk(&Script_gameinithook, "GameInit"); } if (optional_string("$Simulation:")) { st->ParseChunk(&Script_simulationhook, "Simulation"); } if (optional_string("$HUD:")) { st->ParseChunk(&Script_hudhook, "HUD"); } required_string("#End"); } /* if(optional_string("#State Hooks")) { while(optional_string("$State:")) { char buf[NAME_LENGTH]; int idx; stuff_string(buf, F_NAME, sizeof(buf)); idx = gameseq_get_state_idx(buf); if(optional_string("$Hook:")) { if(idx > -1) { GS_state_hooks[idx] = st->ParseChunk(buf); } else { st->ParseChunk(buf); } } } required_string("#End"); } */ if (optional_string("#Conditional Hooks")) { while (st->ParseCondition(filename)); required_string("#End"); } // add tbl/tbm to multiplayer validation list extern void fs2netd_add_table_validation(const char *tblname); fs2netd_add_table_validation(filename); } catch (const parse::ParseException& e) { mprintf(("TABLES: Unable to parse '%s'! Error message = %s.\n", filename, e.what())); return; } }
void ExtractBeEA(Archive &Arc,char *FileName) { if (Arc.HeaderCRC!=Arc.EAHead.HeadCRC) { Log(Arc.FileName,St(MEABroken),FileName); ErrHandler.SetErrorCode(RARX_CRC); return; } if (Arc.EAHead.Method<0x31 || Arc.EAHead.Method>0x35 || Arc.EAHead.UnpVer>PACK_VER) { Log(Arc.FileName,St(MEAUnknHeader),FileName); return; } ComprDataIO DataIO; Unpack Unpack(&DataIO); Unpack.Init(); Array<byte> UnpData(Arc.EAHead.UnpSize); DataIO.SetUnpackToMemory(&UnpData[0],Arc.EAHead.UnpSize); DataIO.SetPackedSizeToRead(Arc.EAHead.DataSize); DataIO.EnableShowProgress(false); DataIO.SetFiles(&Arc,NULL); Unpack.SetDestSize(Arc.EAHead.UnpSize); Unpack.DoUnpack(Arc.EAHead.UnpVer,false); if (Arc.EAHead.EACRC!=~DataIO.UnpFileCRC) { Log(Arc.FileName,St(MEABroken),FileName); ErrHandler.SetErrorCode(RARX_CRC); return; } int fd = open(FileName,O_WRONLY); if (fd==-1) { Log(Arc.FileName,St(MCannotSetEA),FileName); ErrHandler.SetErrorCode(RARX_WARNING); return; } int AttrPos=0; while (AttrPos<Arc.EAHead.UnpSize) { unsigned char *CurItem=&UnpData[AttrPos]; int NameSize=CurItem[0]+((int)CurItem[1]<<8); int Type=CurItem[2]+((int)CurItem[3]<<8)+((int)CurItem[4]<<16)+((int)CurItem[5]<<24); int Size=CurItem[6]+((int)CurItem[7]<<8)+((int)CurItem[8]<<16)+((int)CurItem[9]<<24); char Name[1024]; if (NameSize>=sizeof(Name)) { Log(Arc.FileName,St(MCannotSetEA),FileName); ErrHandler.SetErrorCode(RARX_WARNING); break; } memcpy(Name,CurItem+10,NameSize); Name[NameSize]=0; if (fs_write_attr(fd,Name,Type,0,CurItem+10+NameSize,Size)==-1) { Log(Arc.FileName,St(MCannotSetEA),FileName); ErrHandler.SetErrorCode(RARX_WARNING); break; } AttrPos+=10+NameSize+Size; } close(fd); mprintf(St(MShowEA)); }
int sendMOAIndices (Master * master, int ProcDest, MOA_rec * MOA_in, long waveNo) { unsigned int membersize, maxsize; int position; int dest, tag; char *buffer, cmessage, msg[SHORT_MESSAGE_SIZE]; long i, j, PrevCellsCount, lmessage; unsigned long ulmessage; long * ind = NULL; long * ind2 = NULL; int MPI_return; MPI_Request request; /* Send the MOA Buffer*/ /*3) Wave No */ MPI_return = NBSend(&waveNo, 1, MPI_TYPE_PWave, ProcDest, MPI_TAG_PWave, &request ); checkMPIErrorCode (3, MPI_return); /*3) dimn */ MPI_return = NBSend(&MOA_in->dimn, 1, MPI_TYPE_PDimn, ProcDest, MPI_TAG_PDimn, &request ); checkMPIErrorCode (3, MPI_return); /*4) shape */ for (i=0;i<MOA_in->dimn;i++) { lmessage = MOA_in->shape[i]; MPI_return = NBSend(&MOA_in->shape[i], 1, MPI_TYPE_PShape, ProcDest, MPI_TAG_PShape, &request ); checkMPIErrorCode (3, MPI_return); } //5) elements_ub ulmessage = MOA_in->elements_ub; MPI_return = NBSend(&ulmessage, 1, MPI_TYPE_PElmUB, ProcDest, MPI_TAG_PElmUB, &request ); checkMPIErrorCode (3, MPI_return); //6) indexes sprintf (msg,"Master sending %ld elements_ub\n", MOA_in->elements_ub); mprintf(12, msg, 3); ind = (long *) mmalloc (sizeof(long) * master->msaAlgn->dimn); for (i=0;i<MOA_in->elements_ub;i++) { ulmessage = MOA_in->indexes[i]; sprintf (msg,"Master sending index[%ld] %ld\n", i, MOA_in->indexes[i]); mprintf(12, msg, 3); MPI_return = NBSend(&ulmessage, 1, MPI_TYPE_PIndices, ProcDest, MPI_TAG_PIndices, &request ); checkMPIErrorCode (3, MPI_return); sprintf (msg, "Master finished sending indices with i = %ld\n", i); mprintf(12, msg, 3); } // 7) Send Corresponding Residues from the Sequences read //Gamma_Inverse(i, MOA_in->shape, MOA_in->dimn, ind); //if (isLowerBorderCell(ind, MOA_in->dimn) == 0) { //Gamma_Inverse(MOA_in->indexes[i], master->msaAlgn->shape, master->msaAlgn->dimn, ind); ind2 = (long *) mmalloc (sizeof(long) * master->msaAlgn->dimn); for (i=0;i<MOA_in->dimn;i++) ind [i] = 0; Gamma_Inverse(MOA_in->indexes[0], master->msaAlgn->shape, master->msaAlgn->dimn, ind2); for (i=0;i<MOA_in->dimn;i++) { cmessage = master->sequences[i][ind2[i]]; MPI_return = NBSend(&cmessage, 1, MPI_TYPE_PResidue, ProcDest, MPI_TAG_PResidue, &request ); checkMPIErrorCode (3, MPI_return); sprintf(msg, "sent sequences[%ld][%ld] = %c to Processor = %d\n", i, ind2[i], cmessage, ProcDest); mprintf(12, msg, 3); } for (i=0;i< MOA_in->dimn;i++) { for (j=1;j< MOA_in->shape[i];j++) { ind[i] = j; lmessage = Gamma (ind, MOA_in->dimn, MOA_in->shape, MOA_in->dimn, 1); Gamma_Inverse(MOA_in->indexes[lmessage], master->msaAlgn->shape, master->msaAlgn->dimn, ind2); cmessage = master->sequences[i][ind2[i]]; MPI_return = NBSend(&cmessage, 1, MPI_TYPE_PResidue, ProcDest, MPI_TAG_PResidue, &request ); checkMPIErrorCode (3, MPI_return); sprintf(msg, "sent sequences[%ld][%ld] = %c to Processor = %d\n", i, ind2[j], cmessage, ProcDest); mprintf(12, msg, 3); ind[i]=0; } } if (ind != NULL) free (ind); if (ind2 != NULL) free (ind2); return 0; }
void CommandData::BadSwitch(char *Switch) { mprintf(St(MUnknownOption),Switch); ErrHandler.Exit(USER_ERROR); }
void opengl_extensions_init() { opengl_get_extensions(); // if S3TC compression is found, then "GL_ARB_texture_compression" must be an extension Use_compressed_textures = Is_Extension_Enabled(OGL_EXT_TEXTURE_COMPRESSION_S3TC); Texture_compression_available = Is_Extension_Enabled(OGL_ARB_TEXTURE_COMPRESSION); // Swifty put this in, but it's not doing anything. Once he uses it, he can uncomment it. //int use_base_vertex = Is_Extension_Enabled(OGL_ARB_DRAW_ELEMENTS_BASE_VERTEX); //allow VBOs to be used if ( !Cmdline_nohtl && !Cmdline_novbo && Is_Extension_Enabled(OGL_ARB_VERTEX_BUFFER_OBJECT) ) { Use_VBOs = 1; } if ( !Cmdline_no_pbo && Is_Extension_Enabled(OGL_ARB_PIXEL_BUFFER_OBJECT) ) { Use_PBOs = 1; } // setup the best fog function found if ( !Fred_running ) { if ( Is_Extension_Enabled(OGL_EXT_FOG_COORD) ) { OGL_fogmode = 2; } else { OGL_fogmode = 1; } } // if we can't do cubemaps then turn off Cmdline_env if ( !(Is_Extension_Enabled(OGL_ARB_TEXTURE_CUBE_MAP) && Is_Extension_Enabled(OGL_ARB_TEXTURE_ENV_COMBINE)) ) { Cmdline_env = 0; } if ( !(Is_Extension_Enabled(OGL_EXT_GEOMETRY_SHADER4) && Is_Extension_Enabled(OGL_EXT_TEXTURE_ARRAY) && Is_Extension_Enabled(OGL_ARB_DRAW_ELEMENTS_BASE_VERTEX)) ) { Cmdline_shadow_quality = 0; mprintf((" No hardware support for shadow mapping. Shadows will be disabled. \n")); } if ( !Cmdline_noglsl && Is_Extension_Enabled(OGL_ARB_SHADER_OBJECTS) && Is_Extension_Enabled(OGL_ARB_FRAGMENT_SHADER) && Is_Extension_Enabled(OGL_ARB_VERTEX_SHADER) ) { int ver = 0, major = 0, minor = 0; const char *glsl_ver = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); sscanf(glsl_ver, "%d.%d", &major, &minor); ver = (major * 100) + minor; GLSL_version = ver; // we require a minimum GLSL version if (!is_minimum_GLSL_version()) { mprintf((" OpenGL Shading Language version %s is not sufficient to use GLSL mode in FSO. Defaulting to fixed-function renderer.\n", glGetString(GL_SHADING_LANGUAGE_VERSION) )); } } // can't have this stuff without GLSL support if ( !is_minimum_GLSL_version() ) { Cmdline_normal = 0; Cmdline_height = 0; Cmdline_postprocess = 0; Cmdline_shadow_quality = 0; Cmdline_no_deferred_lighting = 1; } if ( GLSL_version < 120 || !Is_Extension_Enabled(OGL_EXT_FRAMEBUFFER_OBJECT) || !Is_Extension_Enabled(OGL_ARB_FLOATING_POINT_TEXTURES) ) { mprintf((" No hardware support for deferred lighting. Deferred lighting will be disabled. \n")); Cmdline_no_deferred_lighting = 1; Cmdline_no_batching = true; } if (is_minimum_GLSL_version()) { GLint max_texture_units; glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &max_texture_units); // we need enough texture slots for this stuff to work if (max_texture_units < 6) { mprintf(( "Not enough texture units for height map support. We need at least 6, we found %d.\n", max_texture_units )); Cmdline_height = 0; } else if (max_texture_units < 5) { mprintf(( "Not enough texture units for height and normal map support. We need at least 5, we found %d.\n", max_texture_units )); Cmdline_normal = 0; Cmdline_height = 0; } else if (max_texture_units < 4) { mprintf(( "Not enough texture units found for GLSL support. We need at least 4, we found %d.\n", max_texture_units )); GLSL_version = 0; } } }
// game init void ssm_init() { int rval; ssm_info bogus, *s; char weapon_name[NAME_LENGTH]; if ((rval = setjmp(parse_abort)) != 0) { mprintf(("TABLES: Unable to parse '%s'! Error code = %i.\n", "ssm.tbl", rval)); return; } read_file_text("ssm.tbl", CF_TYPE_TABLES); reset_parse(); // parse the table Ssm_info_count = 0; while(!optional_string("#end")){ // another ssm definition if(optional_string("$SSM:")){ // pointer to info struct if(Ssm_info_count >= MAX_SSM_TYPES){ s = &bogus; } else { s = &Ssm_info[Ssm_info_count]; } // name stuff_string(s->name, F_NAME, NAME_LENGTH); // stuff data required_string("+Weapon:"); stuff_string(weapon_name, F_NAME, NAME_LENGTH); required_string("+Count:"); stuff_int(&s->count); required_string("+WarpRadius:"); stuff_float(&s->warp_radius); required_string("+WarpTime:"); stuff_float(&s->warp_time); // According to fireballs.cpp, "Warp lifetime must be at least 4 seconds!" if ( (s->warp_time) < 4.0f) { // So let's warn them before they try to use it, shall we? Warning(LOCATION, "Expected a '+WarpTime:' value equal or greater than 4.0, found '%f' in weapon '%s'.\n Setting to 4.0, please check and set to a number 4.0 or greater!\n", s->warp_time, weapon_name); // And then make the Assert obsolete -- Zacam s->warp_time = 4.0f; } required_string("+Radius:"); stuff_float(&s->radius); required_string("+Offset:"); stuff_float(&s->offset); if (optional_string("+HUD Message:")) stuff_boolean(&s->send_message); else s->send_message = true; if (optional_string("+Custom Message:")) { stuff_string(s->message, F_NAME, NAME_LENGTH); s->use_custom_message = true; } // see if we have a valid weapon s->weapon_info_index = -1; s->weapon_info_index = weapon_info_lookup(weapon_name); if(s->weapon_info_index >= 0){ // valid Ssm_info_count++; } } } }