bool Model::Initialize(
    const ModelType& modelDesc,
    ComPtr<ID3D11Device> const device,
    const void* shaderBCode,
    const size_t bcodeLength,
    const std::shared_ptr<MaterialFactory> materialFactory)
{
    dimensions = {};
    initDimensions = {};

    if (!LoadModel(modelDesc.modelFilename, device, shaderBCode, bcodeLength))
    {
        return false;
    }

    material = materialFactory->getMaterial(device, modelDesc.materialFilename);
    if (!material) return false;

    return true;
}
Example #2
0
/*
================
idClipModel::idClipModel
================
*/
idClipModel::idClipModel( const idClipModel *model ) {
	enabled = model->enabled;
	entity = model->entity;
	id = model->id;
	owner = model->owner;
	origin = model->origin;
	axis = model->axis;
	bounds = model->bounds;
	absBounds = model->absBounds;
	material = model->material;
	contents = model->contents;
	collisionModelHandle = model->collisionModelHandle;
	traceModelIndex = -1;
	if ( model->traceModelIndex != -1 ) {
		LoadModel( *GetCachedTraceModel( model->traceModelIndex ) );
	}
	renderModelHandle = model->renderModelHandle;
	clipLinks = NULL;
	touchCount = -1;
}
Example #3
0
void SpawnPlayer(float x,float y,float z)
{
  

  entity *testmap;
  
  testmap = newentity();
  testmap->model = LoadModel("models/ship.obj", 0,0.4f);
  if(testmap->model != NULL)
    testmap->shown = 1;
  else testmap->shown = 0;

  testmap->texture = LoadModelTexture("models/ship.png",256,256);
  testmap->self = testmap;
  testmap->shown = 1;
  testmap->alpha = 255;
  testmap->sprite_model = 2;
  testmap->scale.x = 1.0f;
  testmap->scale.y = 1.0f;
  testmap->scale.z = 1.0f;
  testmap->s.x = x;
  testmap->s.y = y;
  testmap->s.z = z;
  testmap->v.x = 1;
  testmap->box.x = testmap->model->center[0];
  testmap->box.y = testmap->model->center[1];
  testmap->box.z = testmap->model->center[2];
  testmap->box.w = testmap->model->dimensions[0];
  testmap->box.h = testmap->model->dimensions[1];
  testmap->box.d = testmap->model->dimensions[2];
  testmap->state=0;
  testmap->think = tileThink;
  testmap->touch = PlayerTouch;
  testmap->frame=0;
  testmap->health=1;
  testmap->solid=1;
  testmap->totalframes=10;
  testmap->keyframe=0;
  testmap->nextkeyframe=1;
  playdead=0;
}
Example #4
0
bool ModelClass::Initialize(ID3D10Device* device, char* modelFilename)
{
    bool result;


    // Load in the model data.
    result = LoadModel(modelFilename);
    if(!result)
    {
        return false;
    }

    // Initialize the vertex and index buffer that hold the geometry for the model.
    result = InitializeBuffers(device);
    if(!result)
    {
        return false;
    }

    return true;
}
Example #5
0
void CRichModel::Preprocess()
{
    if (fBePreprocessed)
        return;
    if (!m_fBeLoaded)
    {
        LoadModel();
    }

    if (!fLocked)
    {
        fLocked = true;
        CreateEdgesFromVertsAndFaces();
        CollectAndArrangeNeighs();
        ComputeNumOfHoles();
        ComputeAnglesAroundVerts();
        ComputePlanarCoordsOfIncidentVertForEdges();
        fBePreprocessed = true;
        fLocked = false;
    }
}
Example #6
0
Model* LoadModelPlus(const char* name/*,
			GLuint program,
			char* vertexVariableName,
			char* normalVariableName,
			char* texCoordVariableName*/)
{
	Model *m;
	
	m = LoadModel(name);
	
	glGenVertexArrays(1, &m->vao);
	glGenBuffers(1, &m->vb);
	glGenBuffers(1, &m->ib);
	glGenBuffers(1, &m->nb);
	if (m->texCoordArray != NULL)
		glGenBuffers(1, &m->tb);
		
	ReloadModelData(m);
	
	return m;
}
	void CoreDelegateImpl::OnCreate()
	{
		Core::GetGlobalObject<InputSystem>()->AddSubscriber(&m_input_subs);
		Core::GetGlobalObject<InputSystem>()->AddSubscriber(&g_camera_controller);
		auto p_load_manager = Core::GetGlobalObject<Resources::ResourceManager>();
		p_load_manager->LoadResourceSet("..\\..\\..\\Samples\\Resources\\ResourceSets\\render_testing.res");

		LoadModel();		
		CreateMesh();
		Core::GetGlobalObject<Render::FontManager>()->LoadFont("Arial", Render::FontSettings(), "..\\..\\..\\Samples\\Resources\\Fonts\\arial.ttf");
		auto& world = Core::GetApplication()->GetWorld();
		auto& camera = world.GetCamera();
		static SDK::Vector3 shift{ 5.f, -5.f, -50.f };
		static SDK::Vector3 look_at{ -500,-500, 1500 };
		camera.LookAt(shift, look_at);

		world.GetFrustum().SetFOV(80 * Math::DEG2RAD);
		world.GetFrustum().SetFarClipDistance(1000.f);
		world.GetFrustum().SetNearClipDistance(0.5f);
		Core::GetRenderer()->SetClearColor(Color(128, 112, 112, 255));
	}
Example #8
0
void SpawnMine(float x,float y,float z, float vx, float vy, float vz, float side)
{
  

  entity *testmap;
  
  testmap = newentity();
  testmap->model = LoadModel("models/mine.obj", 0,1.0f);
  if(testmap->model != NULL)
    testmap->shown = 1;
  else testmap->shown = 0;

  testmap->texture = LoadModelTexture("models/mine.png",256,256);
  testmap->self = testmap;
  testmap->shown = 1;
  testmap->alpha = 255;
  testmap->sprite_model = 4;
  testmap->scale.x = 1.0f;
  testmap->scale.y = 1.0f;
  testmap->scale.z = 1.0f;
  testmap->s.x = x;
  testmap->s.y = y;
  testmap->s.z = z;
  testmap->v.x = vx;
  testmap->v.y = vy;
  testmap->v.z = vz;
  testmap->state=side;
  testmap->box.x = testmap->model->center[0];
  testmap->box.y = testmap->model->center[1];
  testmap->box.z = testmap->model->center[2];
  testmap->box.w = testmap->model->dimensions[0];
  testmap->box.h = testmap->model->dimensions[1];
  testmap->box.d = testmap->model->dimensions[2];
  testmap->think = mineThink;
  testmap->frame=0;
  testmap->solid=1;
  testmap->totalframes=10;
  testmap->keyframe=0;
  testmap->nextkeyframe=1;
}
BulletModel::BulletModel(glm::vec3 dir) : Lib3dsModel(), mAge(0)
{
	SetPhysicsType(Model::Dynamic);
	SetScaling(glm::vec3(0.5, 0.5, 0.5));

	mDirection = glm::normalize(dir);

	float verticalAngle = -glm::asin(mDirection.y); // approximately good
	float horizontalAngle = -((-3.14159 / 2.0) + glm::atan(mDirection.z / mDirection.x));

	// ATAN2
	if (mDirection.x < 0){
		if (mDirection.z >= 0){
			horizontalAngle -= 3.14159;
		}
		else{
			horizontalAngle += 3.14159;
		}
	}

	//std::cout << "Bullet model vAngle: " << verticalAngle << " hAngle " << horizontalAngle  << " x:  " << direction.x << " z: " << direction.z << std::endl;

	q3Quaternion rot_vert( q3Vec3(1,0,0), verticalAngle);
	q3Quaternion rot_horiz(q3Vec3(0,1,0), horizontalAngle);

	mRotation = rot_horiz * rot_vert;

	mScaling = glm::vec3(0.01, 0.01, 0.01);
	mMeshes.insert(13);
	mFileName = "../Assets/Objects/bombs.3ds";

	LoadModel();



	//mMaxAge = 90; // 90 second exipr date

}
Example #10
0
void Game::processMapFileLine(string line)	{

	char* token;
	char str[512];

	strncpy(str, line.c_str(), 512);
	token = strtok(str, WHITESPACE);

	if( token == NULL )
		return;

	if( !strcmp(token, "map") )	{
		token = strtok(NULL, WHITESPACE);
		LoadMap(token);
		Con_print("MAP: Loading OBJ Map: %s", token);
	}
	else if( !strcmp(token, "md2") )	{
		token = strtok(NULL, WHITESPACE);
		LoadModel(token);
		Con_print("MAP: Loading MD2 Model: %s", token);
	}

}
bool LoadAssets()
{
	// 텍스처 로딩
	gpStoneDM = LoadTexture("Fieldstone_DM.tga");
	if (!gpStoneDM)
	{
		return false;
	}

	gpStoneSM = LoadTexture("Fieldstone_SM.tga");
	if (!gpStoneSM)
	{
		return false;
	}

	gpStoneNM = LoadTexture("Fieldstone_NM.tga");
	if (!gpStoneNM)
	{
		return false;
	}

	// 쉐이더 로딩
	gpNormalMappingShader = LoadShader("NormalMapping.fx");
	if (!gpNormalMappingShader)
	{
		return false;
	}

	// 모델 로딩
	gpSphere = LoadModel("spherewithtangent.x");
	if (!gpSphere)
	{
		return false;
	}

	return true;
}
Example #12
0
void playergraphic(float x,float y,float z)
{

  entity *player;
  
  player = newentity();
  player->model = LoadModel(playerModel, 3,playerModelScale);
  if(player->model != NULL)
    player->shown = 1;
  else player->shown = 0;

  player->shaderTexture = loadShader("Shader.txt");
  player->self = player;
  player->sprite_model = 7;
  player->scale.x = 8.0f;
  player->scale.y = 8.0f;
  player->scale.z = 8.0f;
  player->modelColor[0] = playerColor.x;
  player->modelColor[1] = playerColor.y;
  player->modelColor[2] = playerColor.z;
  player->modelColor[3] = 1.0f;
  player->s.x = x;
  player->s.y = y;
  player->s.z = z;
  player->think=graplayerupdate;

  player->frame=0;
  player->totalframes=10;
  player->keyframe=0;
  player->nextkeyframe=0;
  player->rotation.x=0.0f;
  player->rotation.y=0.0f;
  player->rotation.z=0.0f;


}
Example #13
0
bool StaticMeshComponent::Initialise(ID3D11Device* device, char* modelFilename, WCHAR* textureFilename)
{
	bool result;
	
	result = LoadModel(modelFilename);
	if (!result)
	{
		return false;
	}

	result = InitialiseBuffers(device);
	if (!result)
	{
		return false;
	}

	result = LoadTexture(device, textureFilename);
	if (!result)
	{
		return false;
	}

	return true;
}
Example #14
0
void Pong::LoadAssets(void)
{
	std::cout << "\nLoading Assets..." << std::endl;
	LoadModel("Assets/Meshes/Cube.obj");
	LoadModel("Assets/Meshes/Paddle.obj");
	LoadModel("Assets/Meshes/WorldBounds.obj");
	LoadModel("Assets/Meshes/Skybox.obj");
	LoadModel("Assets/Meshes/Horse.obj");
	LoadModel("Assets/Meshes/Elephant.obj");
	
	gameObjectRegister.push_back(new Ball(modelRegister[0], "Assets/Textures/WhiteTexture.bmp"));
	gameObjectRegister.push_back(new Paddle(glm::vec3(-25.0f, 0.0f, 0.0f), modelRegister[1], "Assets/Textures/WhiteTexture.bmp"));
	gameObjectRegister.push_back(new Paddle(glm::vec3(25.0f, 0.0f, 0.0f), modelRegister[1], "Assets/Textures/WhiteTexture.bmp"));
	gameObjectRegister.push_back(new WorldBounds(modelRegister[2], "Assets/Textures/WhiteTexture.bmp"));
	gameObjectRegister.push_back(new GUI(glm::vec3(0.0f, 25.0f, 0.0f), modelRegister[0], "Assets/Textures/WhiteTexture.bmp"));
	gameObjectRegister.push_back(new Skybox(modelRegister[0], "Assets/Textures/BlackTexture.bmp"));
	std::cout << "Assets Loaded OK!" << std::endl;

	std::cout << "\nInitialising Vertex Arrays and Buffers..." << std::endl;
	for (int i = 0; i < gameObjectRegister.size(); i++)
	{
		gameObjectRegister[i]->Init_ShaderObjects(shaderLocations);
	}
}
Example #15
0
BOOL Crecord_playerApp::InitInstance() {

    AfxEnableControlContainer();

#ifdef _AFXDLL
    Enable3dControls();         // Call this when using MFC in a shared DLL
#else
    Enable3dControlsStatic();   // Call this when linking to MFC statically
#endif

    g_main_dlg = new Crecord_playerDlg;
  m_pMainWnd = g_main_dlg;

  g_main_dlg->Create(IDD_record_player_DIALOG,NULL);
    
    // create a new world
  world = new cWorld();

  // set background color
  world->setBackgroundColor(0.0f,0.0f,0.0f);

  // Create a camera
  camera = new cCamera(world);
  world->addChild(camera);

  // Create a light source and attach it to camera
  light = new cLight(world);
  light->setEnabled(true);
  light->setPos(cVector3d(2,1,1));

  // define camera position
  flagCameraInMotion = false;

  camera->set(cVector3d(2,0,1), cVector3d(0,0,0), cVector3d(0,0,1));

  // create a display for graphic rendering
  viewport = new cViewport(g_main_dlg->m_gl_area_hwnd, camera, true);
  viewport->setStereoOn(false);

  // init var
  m_rotPos = 0;
  m_rotVel = 0;
  m_inertia = 0.04;
  m_clock.initialize();
  m_lastGoodPosition = 0.0;

  m_reduction = 5.4*10;
  m_cpt = 120*4;          
  m_desiredPos = 0.0;
  m_P = 0.4;
  m_I = 0.0014;
  m_integratorVal = 0.0;
  m_D = 0.02;

  m_lastAngle = 0.0;

  m_velocity = 0;
  m_velocityOld = 0;

  m_RFDInitialAngle = 0.0;
  m_inContact = false;

  LoadModel(TURNTABLE_MODEL);

  object->translate(0,0,-0.3);

  // set stiffness
  double stiffness = (double)35;
  object->setStiffness(stiffness, true);

  // Initialize sound device and create audio stream
  if (!BASS_Init(1,44100,0,0,NULL))
      _cprintf("Init error %d\n", BASS_ErrorGetCode());
    
  // Load a record onto the record player
  load_record(0);
  
  object->computeGlobalPositions(false);
  world->computeGlobalPositions(false);

  return TRUE;
}
Example #16
0
bool GLFramework::LoadModel(const char * path)
{
	bool success = true;
	//find extension
	std::string sPath(path);
	std::string ext = sPath.substr(sPath.find_last_of('.'));

	Geometry geometry;

	if (ext == ".obj")
	{
		std::vector<tinyobj::shape_t> shapes;
		std::vector<tinyobj::material_t> materials;
		std::string err = tinyobj::LoadObj(shapes, materials, path);
		if (err.length() != 0)
		{
			std::cout << "Error loading OBJ file:\n" << err << std::endl;
			success = false;
		}

		//hard coding only using first shape, can change to loop here
		if (success)
		{
			auto shape = shapes[0];
			auto mesh = shape.mesh;

			geometry.vertices.resize(mesh.positions.size());

			uint posIndex = 0;
			uint normalIndex = 0;
			uint UVIndex = 0;
			bool hasNormals = mesh.normals.size() == mesh.positions.size();
			bool hasUVs = mesh.texcoords.size() == mesh.positions.size();
			//obj has vectors of floats, my struct and shaders uses glm vecs so need to build myself
			for (uint vertexCount = 0; posIndex < mesh.positions.size(); vertexCount++)
			{
				float x = mesh.positions[posIndex++];
				float y = mesh.positions[posIndex++];
				float z = mesh.positions[posIndex++];
				geometry.vertices[vertexCount].position = vec4(x, y, z, 1);

				if (hasNormals)
				{
					x = mesh.normals[normalIndex++];
					y = mesh.normals[normalIndex++];
					z = mesh.normals[normalIndex++];
					geometry.vertices[vertexCount].normal = vec4(x, y, z, 1);
				}

				if (hasUVs)
				{
					x = mesh.texcoords[UVIndex++];
					y = mesh.texcoords[UVIndex++];
					geometry.vertices[vertexCount].UV = vec2(x, y);
				}
			}

			geometry.indices = mesh.indices;
		}
	}
	else if (ext == ".fbx")
	{


		FBXFile file;
		success = file.load(path, FBXFile::UNITS_METER, false, false, false);
		if (!success)
		{
			std::cout << "Error loading FBX file:\n";
		}
		else
		{
			//hardcoding to use single mesh, can loop here if needed.
			FBXMeshNode* mesh = file.getMeshByIndex(0);
			geometry.vertices.resize(mesh->m_vertices.size());

			for (int i = 0; i < mesh->m_vertices.size(); i++)
			{
				auto xVert = mesh->m_vertices[i];
				geometry.vertices[i].position = xVert.position;
				geometry.vertices[i].color = xVert.colour;
				geometry.vertices[i].normal = xVert.normal;
				geometry.vertices[i].UV = xVert.texCoord1;
			}

			geometry.indices = mesh->m_indices;

			file.unload();
		}

	}
	else
	{
		std::cout << "Unsupported format. Only support .obj or .fbx files.\n";
		success = false;
	}
	if (!success)
	{
		return false;
	}

	LoadModel(geometry);

	return true;
}
Example #17
0
/*
====================
idRenderModelMD5::InitFromFile
====================
*/
void idRenderModelMD5::InitFromFile( const char* fileName )
{
	name = fileName;
	LoadModel();
}
Example #18
0
int main( int argc, char *argv[])
{
  ImodApp app;
  ImodView vi;
  IloadInfo li;
  FILE *fin        = NULL;
  FILE *mfin       = NULL;
  char *plistfname = NULL;
  char *anglefname = NULL;
  int xyzwinopen   = FALSE;
  int sliceropen   = FALSE;
  int zapOpen      = FALSE;
  int modelViewOpen= FALSE;
  bool print_wid   = false;
  int fillCache    = FALSE;
  bool newModelCreated = false;
  int i      = 0;
  int nx, ny, nz, mode;
  int minxpiece, numXpieces, xoverlap, minypiece, numYpieces, yoverlap;
  float initAngles[3], initZoom;
  Ipoint initCenter;
  int setAngles = 0;
  int setCenter = 0;
  int setZoom = 0;
  int frames = 0;
  int firstfile = 0;
  int lastimage;
  int  pathlen;
  int nframex = 0;
  int nframey = 0;
  int overx = 0;
  int overy = 0;
  int doStartup = 0;
  QString qname;
  QStringList plFileNames;
  int doFork = 1;
  char *cmdLineStyle = NULL;
  int doImodv = 0;
  int rawSet = 0;
  int overEntered = 0;
  int useMdoc = 0;
  bool useStdin = false;
  bool dataFromStdin = false;
  bool anyHavePieceList = false;
  bool anyImageFail = false;
  bool useChooserPlug = false;
  int argScan, argcHere;
  QRect infoGeom;
  StartupForm *startup = NULL;

  /* Initialize data. */
  App = &app;
  App->rgba = 1;    /* Set to 1 to force RGB visual */
  App->exiting = 0;
  App->closing = 0;
  App->cvi = &vi;
  App->base = Rampbase;
  App->convertSnap = 0;
  App->glInitialized = 0;
  App->chooserPlugin = 0;

  /* Set up fixed indexes */
  App->background   = IMOD_BACKGROUND;
  App->foreground   = IMOD_FOREGROUND;
  App->select       = IMOD_SELECT;
  App->shadow       = IMOD_SHADOW;
  App->endpoint     = IMOD_ENDPOINT;
  App->bgnpoint     = IMOD_BGNPOINT;
  App->curpoint     = IMOD_CURPOINT;
  App->ghost        = IMOD_GHOST;
  App->arrow[0]     = IMOD_ARROW;
  App->arrow[1]     = IMOD_ARROW2;
  App->arrow[2]     = IMOD_ARROW3;
  App->arrow[3]     = IMOD_ARROW4;

  /*DNM: prescan for debug, ci and style flags before the display_init */
  /* Cancel forking on debug or -W output, or -L or -R or -h */
  for (i = 1; i < argc; i++){
    if (!strncmp("-D", argv[i], 2)) {
      Imod_debug = TRUE;
      debugKeys = strdup(argv[i] + 2);
      doFork = 0;
    }
    if (!strcmp("-W", argv[i]) || !strcmp("-R", argv[i]) || !strcmp("-h", argv[i]))
      doFork = 0;

    if (!strcmp("-L", argv[i])) {
      doFork = 0;
#if defined(_WIN32) && !defined(QT_THREAD_SUPPORT)
      imodError(NULL, "Error: -L option cannot be used because "
                "3dmod was not built with Qt thread support\n");
      exit(1);
#endif
    }

    if (!strcmp("-ci", argv[i]))
      App->rgba = -1;  /* Set to -1 to force worthless Color index visual */

    if (argv[i][0] == '-' && argv[i][1] == 's' && argv[i][2] == 't'
        && argv[i][3] == 'y' && argv[i][4] == 'l' && argv[i][5] == 'e') {
      if (argv[i][6] == '=')
        cmdLineStyle = strdup(&(argv[i][7]));
      else if (i < argc - 1)
        cmdLineStyle = strdup(argv[i + 1]);
    }
    
    if (!strcmp("-modv", argv[i]) || !strcmp("-view", argv[i]))
      doImodv = 1;

    if (!strcmp("-O", argv[i]))
      doStartup = 1;
    if (argv[i][0] == '-')
      firstfile = i + 1;
  }

#ifndef NO_IMOD_FORK
  /* Fork now to avoid conflicts */
  if (doFork)
    if (fork())
      exit(0);
#endif

#ifdef Q_OS_MACX
  // fix OS X 10.9 font issue https://bugreports.qt-project.org/browse/QTBUG-32789
  // MV_10_8 is not defined in Qt 4.6 etc, this is the value in Qt 4.8
  if (QSysInfo::MacintoshVersion > 0x000A)
    QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif

  /* Open the Qt application */
  // Once we have told Qt about the original arguments, we must not modify argc here
  // Somehow later it accesses the old argument vector with the new number of args
  QApplication qapp(argc, argv);
  argcHere = argc;
  
  /* Set title for error dialogs, and set up to store error strings */
  diaSetTitle("3dmod");
  b3dSetStoreError(1);
  setlocale(LC_NUMERIC, "C");

  ImodPrefs = new ImodPreferences(cmdLineStyle);
  ImodHelp = new ImodAssistant("html", "IMOD.qhc", "3dmod", false, false, "3dmodHelp");

  // Set up the application icon for windows to use
  App->iconPixmap = new QPixmap(QPixmap::fromImage(QImage(b3dicon)));

  // Load in all the imod plugins that we can use (moved up so file chooser available)
  imodPlugInit();

  /* if no input files, open startup window */
  i = strlen(argv[0]);
  if (argv[0][i-1] == 'v')
    doImodv = 1;
  if (argcHere < 2 || (doStartup && doImodv)) {
    useChooserPlug = true;
    startup = new StartupForm(NULL, true, Qt::Window);
    startup->setWindowIcon(*(App->iconPixmap));
    if (doImodv) {
      mrc_init_li(&li, NULL);
      ivwInit(&vi, false);
      vi.li = &li;
      startup->setValues(&vi, argv, firstfile, argcHere, doImodv, plFileNames, 
                         anglefname, useMdoc, xyzwinopen, sliceropen, zapOpen,
                         modelViewOpen, fillCache, ImodTrans, 0, frames,
                         nframex, nframey, overx, overy, overEntered);
    }
    if (startup->exec() == QDialog::Rejected) {
      imod_usage(argv[0]);
      exit(1);
    }
    
    argv = startup->getArguments(argcHere);
    doImodv = 0;
    /*for (i = 0; i < argcHere; i++)
      imodPrintStderr("%s ", argv[i]);
      imodPrintStderr("\n");*/
    doStartup = 0;
  }

  /* Run the program as imodv? */
  i = strlen(argv[0]);
  if (doImodv || argv[0][i-1] == 'v'){
    if (!useChooserPlug)
      App->chooserPlugin = 0;
    imodv_main(argcHere, argv);
    exit(0);
  }

  QDir *curdir = new QDir();

  /* 3/14/11: eliminated old code for out how many imods this user is running. */

  /*******************/
  /* Loop once or twice on arguments; initialize Data each time */

  for (argScan = 0; argScan <= doStartup; argScan++) { 
    mrc_init_li(&li, NULL);
    ivwInit(&vi, false);
    vi.li = &li;
    if (ImodPrefs->loadUshorts())
      vi.rawImageStore = MRC_MODE_USHORT;
    plistfname = NULL;
    xyzwinopen   = FALSE;
    sliceropen   = FALSE;
    zapOpen      = FALSE;
    modelViewOpen= FALSE;
    fillCache    = FALSE;
    ImodTrans  = TRUE;
    frames     = 0;
    nframex = 0;
    nframey = 0;
    overx = 0;
    overy = 0;
    firstfile = 0;
    overEntered = 0;

    /* handle input options. */
    for (i = 1; i < argcHere; i++){
      if (argv[i][0] == '-'){
        if (firstfile) {
          imodError(NULL, "3dmod: invalid to have argument %s after"
                    " first filename\n", argv[i]);
          exit(1);
        }
        switch (argv[i][1]){
        
        case 'c':
          if (argv[i][2] == 'i')
            break;
          /* 1/5/04: eliminated colormap selection option */
          if (argv[i][2] == 'm') {
            if (xcramp_readfalsemap(argv[++i])) {
              qname = b3dGetError();
              imodError(NULL, LATIN1(qname));
            }
            break;
          }
          badOption(argv[i]);
        
        case 'C':
          if (argv[i][2] == 'T')
            vi.stripOrTileCache = 1;
          else if (strlen(argv[i]) > 2)
            badOption(argv[i]);

          /* value ending in m or M is megabytes, store as minus */
          pathlen = strlen(argv[++i]);
          sscanf(argv[i], "%d%*c", &vi.vmSize);
          if (argv[i][pathlen - 1] == 'M' || argv[i][pathlen - 1] == 'm')
            vi.vmSize = -vi.vmSize;
          else if (!vi.vmSize)
            vi.vmSize = HUGE_CACHE;
          vi.keepCacheFull = 0;
          break;
        
        case 'F':
          fillCache = TRUE;
          break;

        case 'x':
          if (argv[i][2] == 'y')
            if(argv[i][3] == 'z'){
              xyzwinopen = TRUE;
              break;
            }
          if (argv[i][2] >= '0' && argv[i][2] <= '9')
            sscanf(argv[i], "-x%d%*c%d", &(li.xmin), &(li.xmax));
          else if (strlen(argv[i]) > 2)
            badOption(argv[i]);
          else
            sscanf(argv[++i], "%d%*c%d", &(li.xmin), &(li.xmax));
          break;
          
        case 'y':
          if (argv[i][2] >= '0' && argv[i][2] <= '9')
            sscanf(argv[i], "-y%d%*c%d", &(li.ymin), &(li.ymax));
          else if (strlen(argv[i]) > 2)
            badOption(argv[i]);
          else
            sscanf(argv[++i], "%d%*c%d", &(li.ymin), &(li.ymax));
          break;
        
        case 'z':
          if (argv[i][2] >= '0' && argv[i][2] <= '9')
            sscanf(argv[i], "-z%d%*c%d", &(li.zmin), &(li.zmax));
          else if (strlen(argv[i]) > 2)
            badOption(argv[i]);
          else
            sscanf(argv[++i], "%d%*c%d", &(li.zmin), &(li.zmax));
          break;
        
        case 's':
          sscanf(argv[++i], "%f%*c%f", &(li.smin), &(li.smax));
          if (li.smin || li.smax)
            iiRawSetScale(li.smin, li.smax);
          else
            vi.equalScaling = 1;
          break;
        
        case 'b':
          sscanf(argv[++i], "%d%*c%d", &(vi.xybin), &(vi.zbin));
          if (!vi.zbin)
            vi.zbin = 1;
          break;

        case 'B':
          sscanf(argv[++i], "%d", &(vi.xybin));
          vi.zbin = vi.xybin;
          break;

        case 'i':
          if (argv[i][2] == 'c') {
            sscanf(argv[++i], "%f%*c%f%*c%f", &initCenter.x, &initCenter.y, 
                   &initCenter.z);
            setCenter = 1;
          } else if (argv[i][2] == 'a') {
            sscanf(argv[++i], "%f%*c%f%*c%f", &initAngles[0], &initAngles[1], 
                   &initAngles[2]);
            setAngles = 1;
          } else if (argv[i][2] == 'z') {
            sscanf(argv[++i], "%f", &initZoom);
            setZoom = 1;
          } else
            badOption(argv[i]);
          break;

        case 'D':
          Imod_debug = TRUE;
          break;
        
        case 'E':
          windowKeys = strdup(argv[++i]);
          break;

        case 'm':
          ImodTrans = FALSE;
          break;
        
        case 'M':
          vi.li->mirrorFFT = -1;
          break;
        
        case 'Y':
          li.axis = 2;
          break;
        
        case 'h':
          imod_usage(argv[0]);
          exit(1);
          break;
        
        case 'p':
          if (argv[i][2] == 'y') {
            vi.imagePyramid = 1;
            break;
          }
          if (strlen(argv[i]) > 2)
            badOption(argv[i]);
          plistfname = argv[++i];
          plFileNames << QDir::toNativeSeparators(curdir->cleanPath(QString(plistfname)));
          break;
        
        case 'a':
          anglefname = argv[++i];
          break;
        
        case 'f':
          frames = 1;
          break;
        
        case 'G':
          vi.grayRGBs = 1;
          break;
        
        case '2':
          vi.dim &= ~4;
          break;
        
        case 'P':
          sscanf(argv[++i], "%d%*c%d", &nframex, &nframey);
          break;
        
        case 'o':
          overEntered = 1;
          sscanf(argv[++i], "%d%*c%d", &overx, &overy);
          break;
        
        case 'S':
          sliceropen = TRUE;
          break;
        
        case 'V':
          modelViewOpen = TRUE;
          break;
        
        case 'Z':
          zapOpen = TRUE;
          break;
        
        case 'T':
          vi.multiFileZ = -1;
          break;
        
        case 'W':
          print_wid = true;
          break;
        
        case 'r':
          if (argv[i][2] == 'i') {
            iiRawSetInverted();
          } else if (strlen(argv[i]) > 2) {
            badOption(argv[i]);
          } else {
            sscanf(argv[++i], "%d,%d,%d", &nx, &ny, &nz);
            iiRawSetSize(nx, ny, nz);
          }
          rawSet = 1;
          break;

        case 't':
          sscanf(argv[++i], "%d", &mode);
          iiRawSetMode(mode);
          rawSet = 1;
          break;

        case 'H':
          sscanf(argv[++i], "%d", &mode);
          iiRawSetHeaderSize(mode);
          rawSet = 1;
          break;

        case 'w':
          iiRawSetSwap();
          rawSet = 1;
          break;
        
        case 'I':
          sscanf(argv[++i], "%d", &mode);
          if (mode)
            vi.rawImageStore = MRC_MODE_USHORT;
          else
            vi.rawImageStore = 0;
          break;

        case 'R':
          dataFromStdin = true;
          break;

        case 'L':
          useStdin = true;
          break;

        case 'O':
          break;
        
        default:
          badOption(argv[i]);
        
        }
      } else if (!firstfile)
        firstfile = i;
    }

    /* First time through when doing startup, open startup and give it 
       options */
    if (!argScan && doStartup) {
      useChooserPlug = true;
      startup = new StartupForm(NULL, true, Qt::Window);
      startup->setWindowIcon(*(App->iconPixmap));
      startup->setValues(&vi, argv, firstfile, argcHere, doImodv, plFileNames,
                         anglefname, useMdoc, xyzwinopen, sliceropen, zapOpen,
                         modelViewOpen, fillCache, ImodTrans, vi.li->mirrorFFT,
                         frames, nframex, nframey, overx, overy, overEntered);
      if (startup->exec() == QDialog::Rejected) {
        imod_usage(argv[0]);
        exit(1);
      }
    
      argv = startup->getArguments(argcHere);
      if (Imod_debug) {
        for (i = 0; i < argcHere; i++)
          imodPrintStderr("%s ", argv[i]);
        imodPrintStderr("\n"); 
      }

      // Run 3dmodv if they asked for it!
      if (argv[0][strlen(argv[0]) - 1] == 'v') {
        imodv_main(argcHere, argv);
        exit(0);
      }
    }
  }
  
  /* If the user did not limit cache and specified Fill cache, then restore
     the flag to keep cache full */
  if (fillCache && vi.vmSize == HUGE_CACHE)
    vi.keepCacheFull = 1;
  
  // If cache is being filled, then cancel strip/tile option
  if (vi.keepCacheFull)
    vi.stripOrTileCache = 0;

  /* Initialize the display system - defer color ramps until image type is known */
  imod_display_init(App, argv);

  /* Add check function for raw and QImage formats after plugins so plugins
     can add them first.  But if any raw options were entered, put raw check 
     first.  But if reading from stdin, put MRC check first! */
  if (dataFromStdin) 
    iiInsertCheckFunction(iiMRCCheck, 0);
  iiAddCheckFunction(iiQImageCheck);
  if (rawSet)
    iiInsertCheckFunction(iiRawCheck,0);
  else
    iiAddCheckFunction(iiRawCheck);
  tiffFilterWarnings();
  iiRegisterQuitCheck(imodQuitCheck);

  /* Try to open the last file if there is one */
  if (firstfile) {
    qname = QDir::toNativeSeparators(QString(argv[argcHere - 1]));

    // first check if it is directory, if so say it is last image
    QFileInfo info(qname);
    if (info.isDir()) {
      lastimage = argcHere - 1;
    } else {
      mfin = fopen(LATIN1(qname), "rb");
      if (mfin == NULL) {

        /* Fail to open, and it is the only filename, then exit */
        if (firstfile == argcHere - 1) {
          imodError(NULL, "Couldn't open input file %s.\n", argv[argcHere - 1]);
          exit(10);
        }
        
        /* But if there are other files, set up to open new model with that name*/
        imodPrintStderr("Model file (%s) not found: opening "
                        "new model by that name.\n", argv[argcHere - 1]);
        
        lastimage = argcHere - 2;
        newModelCreated = true;
        
      } else {
        
        /*
         * Try loading file as a model.  Turn it on if successful
         */
        Model = LoadModel(mfin);
        if (Model) {
          if (Imod_debug)
            imodPrintStderr("Loaded model %s\n", argv[argcHere -1]);
          lastimage = argcHere - 2;
          Model->drawmode = 1;
          
          // Set this now in case image load is interrupted
          Model->csum = imodChecksum(Model);
        } else {
          /* If fail, last file is an image */
          lastimage = argcHere - 1;
        }
        fclose(mfin);
      }
    }
  }
  
  if (dataFromStdin) {

    // Data from stdin: check for contradictory options
    if (li.xmin != -1 || li.xmax != -1 || li.ymin != -1 || li.ymax != -1 ||
        li.zmin != -1 || li.zmax != -1) {
      imodError(NULL, "You cannot set subareas when reading data from stdin\n");
      exit(3);
    }
    if (plistfname || useStdin || rawSet || vi.vmSize || vi.imagePyramid) {
      imodError(NULL, "You cannot use -C, -L, -p, -py, or raw options when "
                "reading data from stdin\n");
      exit(3);
    }
    if (firstfile && lastimage >= firstfile) {
      imodError(NULL, "You cannot enter any image files when reading data from stdin\n");
      exit(3);
    }

    Imod_imagefile = strdup("");
    vi.noReadableImage = 1;
    ivwMultipleFiles(&vi, &Imod_imagefile, 0, 0, anyHavePieceList);

  } else if (lastimage < firstfile && Model) {

    /* If we have a model and no image files before that, then it's a fake image */
    vi.fakeImage = 1;
    Imod_imagefile = NULL;
    vi.numTimes = Model->tmax = imodGetMaxTime(Model);
    
  } else if (!firstfile || lastimage == firstfile) {
    
  /* If there are no filenames, or one image file, then treat as image
    file or IFD.  First get filename if none */
    if (!firstfile) {
      imodVersion(NULL);
      imodCopyright();
      useChooserPlug = true;
      qname = utilOpenFileName(NULL, "3dmod: Select Image file to load:", 0, NULL);
      if (qname.isEmpty()) {
        imodError(NULL, "3DMOD: file not selected\n");
        exit(3);
      }
      Imod_imagefile = strdup(LATIN1(qname));
      
    } else {
      /* Or, just set the image file name */
      Imod_imagefile = strdup(LATIN1(curdir->cleanPath(QString(argv[firstfile]))));
    }
    
    if (Imod_debug){
      imodPrintStderr("Loading %s\n", Imod_imagefile);
    }
   
    qname = QDir::toNativeSeparators(QString(Imod_imagefile));

    // Check if it is directory (again)
    QFileInfo info(qname);
    if (info.isDir()) {
      
      // Get a QDir there and look for files ending in "list" (could add more)
      QDir argDir(qname);
      QStringList filters;
      filters << "*list";
      QStringList dirList = argDir.entryList(filters);
      if (dirList.isEmpty()) {
        imodError(NULL, "3dmod: %s is a directory but it does not contain a file "
                  "ending in \"list\"", Imod_imagefile);
        exit(10);
      }
      if (dirList.size() > 1) {
        imodError(NULL, "3dmod: the directory %s contains more than one file "
                  "ending in \"list\"", Imod_imagefile);
        exit(10);
      }

      // There is one file, now compose name and try to open it
      free(Imod_imagefile);
      qname += QDir::separator() + dirList[0];
      Imod_imagefile = strdup(LATIN1(qname));
    }

    // Now open the argument or the file found in the directory
    vi.fp = fin = fopen(LATIN1(qname), "r");
    if (fin == NULL) {
        imodError(NULL, "Couldn't open input file %s.\n", Imod_imagefile);
        exit(10);
    }
    
    /* A single image file name can be either
    * IMOD image file desc. 
     * or mrc image file.
     */
    vi.ifd = imodImageFileDesc(fin);

    if (Imod_debug)
      imodPrintStderr( "Image file type %d\n", vi.ifd);

    if (vi.ifd) {

      /* The file is an image list */
      if (vi.ifd > 2) {
        imodError(NULL, "3dmod: Image list file version too high.\n");
        exit (11);
      }

      /* take directory path to IFD file as new current directory for reading images */
      Imod_cwdpath = QDir::currentPath();

      Imod_IFDpath = QString(Imod_imagefile);
      pathlen = Imod_IFDpath.lastIndexOf('/');
      if (pathlen < 0)
        Imod_IFDpath = "";
      else {
        Imod_IFDpath.truncate(pathlen + 1);
        QDir::setCurrent(Imod_IFDpath);
        if (Imod_debug)
          imodPrintStderr("chdir %s\n", LATIN1(Imod_IFDpath));
      }

      /* Load list of images and reset current directory */
      ivwLoadIMODifd(&vi, plFileNames, anyHavePieceList, anyImageFail);
      if (!Imod_IFDpath.isEmpty())
        QDir::setCurrent(Imod_cwdpath);

    } else {

      // It is a single image file - build list with this image
      ivwMultipleFiles(&vi, &Imod_imagefile, 0, 0, anyHavePieceList);
    }
  } else {

    /* Multiple image files - build list of images */
    ivwMultipleFiles(&vi, argv, firstfile, lastimage, anyHavePieceList);
  }
   
  // A pyramid is implied if there is any montage and more than one file
  if (vi.numTimes > 1 && ((anyHavePieceList && !frames) || plFileNames.size() > 0) && 
                           !vi.imagePyramid)
    vi.imagePyramid = -1;

  // If pyramid or tile cache, start the class
  if (vi.imagePyramid || vi.stripOrTileCache)
    vi.pyrCache = new PyramidCache(&vi, plFileNames, frames, anyImageFail);

  /* Now look for piece coordinates - moved up from below 1/2/04 */
  if (!vi.fakeImage && vi.numTimes <= 1 && !vi.li->plist && !dataFromStdin) {

    // If there was a piece list entered with an IFD and not here, go load it
    if (vi.ifd && plFileNames.size() > 0 && plistfname == NULL) {
      if (ivwLoadIFDpieceList(LATIN1(plFileNames[0]), vi.li, vi.hdr->nx, vi.hdr->ny,
                              vi.hdr->nz)) {
        imodError(NULL, "3dmod: Error loading piece list file listed in image list file");
        exit (12);
      }
      
    } else {

      /* Otherwise check for piece list file and read it */
      iiPlistLoad(plistfname, vi.li, vi.hdr->nx, vi.hdr->ny, vi.hdr->nz);
    }

    /* Or use the -P specification */
    if (!vi.li->plist && nframex > 0 && nframey > 0)
      mrc_plist_create(vi.li, vi.hdr->nx, vi.hdr->ny, vi.hdr->nz,
                       nframex, nframey, overx, overy);

    /* Or, check for piece coordinates in image header */
    if (!vi.li->plist && !frames && 
        (vi.image->file == IIFILE_MRC || vi.image->file == IIFILE_HDF)) {
      ivwReopen(vi.image);
      if (QFile::exists(QString(vi.image->filename) + ".mdoc"))
        useMdoc = 1;
      iiLoadPCoord(vi.image, useMdoc, vi.li, vi.hdr->nx, vi.hdr->ny,
                   vi.hdr->nz);
      iiClose(vi.image);
    }
          
    // If an overlap was entered and there were piece coordinates, adjust the overlap
    if (vi.li->plist && !nframex && !nframey && overEntered) {
      if (checkPieceList(vi.li->pcoords, 3, vi.li->plist, 1, vi.hdr->nx, &minxpiece, 
                         &numXpieces, &xoverlap) || 
          checkPieceList(vi.li->pcoords + 1, 3, vi.li->plist, 1, vi.hdr->ny, &minypiece,
                         &numYpieces, &yoverlap)) {
        imodError(NULL, "3dmod: Piece coordinates are not on a regular grid so overlap"
                  " cannot be adjusted.\n");
        exit (12);
      }
      if (numXpieces > 1)
        adjustPieceOverlap(vi.li->pcoords, 3, vi.li->plist, vi.hdr->nx, minxpiece,
                           xoverlap, overx);
      if (numYpieces > 1)
        adjustPieceOverlap(vi.li->pcoords + 1, 3, vi.li->plist, vi.hdr->ny, minypiece,
                           yoverlap, overy);
      vi.li->px = (vi.hdr->nx - overx) * (numXpieces - 1) + vi.hdr->nx;
      vi.li->py = (vi.hdr->ny - overy) * (numYpieces - 1) + vi.hdr->ny;
    }

    /* DNM 1/2/04: move adjusting of loading coordinates to fix_li call,
       and move that call into list processing */
  }

  /* A montage is not flippable unless cache full */
  if (vi.li->plist || vi.stripOrTileCache) 
    vi.flippable = 0;
  if (vi.li->axis == 2 && vi.stripOrTileCache) {
    imodError(NULL, "3dmod: You cannot use a tile/strip cache with flipping of Y and Z");
    exit(12);
  }
  if (vi.numTimes > 1 && !vi.imagePyramid && vi.stripOrTileCache) {
    imodError(NULL, "3dmod: You cannot use a tile/strip cache with multiple image files");
    exit(12);
  }

  // Set up a tile cache now
  if (vi.stripOrTileCache && !vi.imagePyramid)
    vi.pyrCache->setupStripOrTileCache();

  /* set the model filename, or set to get a new model with empty name */
  if (Model || newModelCreated) {
    setImod_filename(LATIN1(curdir->cleanPath(QString(argv[argcHere - 1]))));
  } else {
    Imod_filename[0] = 0x00;
    newModelCreated = true;
  }

  // Read tilt angles if any
  if (anglefname)
    ivwReadAngleFile(&vi, anglefname);

  // Disallow use of file chooser plugin if no chooser was used in startup
  if (!useChooserPlug)
    App->chooserPlugin = 0;

  /*********************/
  /* Open Main Window. */
  imod_info_open(); 
  if (Imod_debug)
    imodPuts("info opened");

  if (Model && imodDebug('C'))
    wprint("main set checksum %d\n", Model->csum);

  /* report window before loading data */
  if (print_wid) {
    unsigned int winID = (unsigned int)ImodInfoWin->winId();
    imodPrintStderr("Window id = %u\n", winID);
    if (Imod_debug)
      wprint("Window id = %u\n", winID);
  }

  /* Get the clipboard messaging object on heap (doesn't work on stack!) */
  if (print_wid || useStdin)
    ClipHandler = new ImodClipboard(useStdin, true);
  App->listening = (print_wid ? 1 : 0) + (useStdin ? 2 : 0);

  // Safe to delete startup now, we have all the arguments it was storing
  delete startup;

  /********************************************/
  /* Load in image data, set up image buffer. */

  /* Finish setting up and loading images */
  errno = 0;
  QTime loadTime;
  loadTime.start();
  if (ivwLoadImage(&vi)){
    qname = b3dGetError();
    qname += "3dmod: Fatal Error -- while reading image data.\n";
    if (errno) 
      qname += QString("System error: ") + QString(QString(strerror(errno)));
    imodError(NULL, LATIN1(qname));
    exit(3);
  }
  iiRegisterQuitCheck(NULL);

  // Now we can set to middle Z
  if (ImodPrefs->startAtMidZ())
    vi.zmouse = (int)(vi.zsize / 2);

  if (Imod_debug)
    imodPrintStderr("Loading time %.3f\n", loadTime.elapsed() / 1000.);

  /* 11/13/06: remove setting of time flag in new model */

  /* Fill cache if user specified it - loader already filled if keepCacheFull*/
  if (fillCache && vi.vmSize)
    imodCacheFill(&vi);

  if (Imod_debug) 
    imodPuts("Read image data OK.");

  /* DNM 1/1/04: eliminate filename output, it is all over the place */
  if (vi.fakeImage)
    wprint("\nNo image loaded.\n");

  delete curdir;
  ImodInfoWin->manageMenus();

  /*************************************/
  /* add all work procs and time outs. (DNM: no more for imodv) */

  /* imodv_add_anim(); */
  imod_start_autosave(App->cvi);

  /* Satisfy the lawyers. */
  wprint("3dmod %s Copyright %s\n"
         "Regents of the Univ. of Colo.\n", 
         VERSION_NAME, COPYRIGHT_YEARS);
  imod_draw_window();
  xcramp_setlevels(App->cvi->cramp,App->cvi->black,App->cvi->white);

  // Set mouse center and constrain it
  if (setCenter) {
    vi.xmouse = initCenter.x;
    vi.ymouse = initCenter.y;
    vi.zmouse = initCenter.z;
    ivwBindMouse(&vi);
    initCenter.x = vi.xmouse;
    initCenter.y = vi.ymouse;
    initCenter.z = vi.zmouse;
  }

  /*********************************/
  /* Open up default Image Windows. */
  if (xyzwinopen)
    xxyz_open(&vi);
  if (sliceropen)
    slicerOpen(&vi, 0);
  if (modelViewOpen) {
    imodv_open();
    imodvOpenSelectedWindows(windowKeys);
  }
  if (zapOpen || !(xyzwinopen || sliceropen || modelViewOpen)) {
    imod_zap_open(&vi, 0); 
    if (setCenter)
      ivwSetTopZapCenter(&vi, vi.xmouse, vi.ymouse, B3DNINT(vi.zmouse), false);
    if (setZoom)
      ivwSetTopZapZoom(&vi, initZoom, false);
  }
  if (Imod_debug)  
    imodPuts("initial windows opened");
  if (App->rgba)
    imod_info_setbw(App->cvi->black, App->cvi->white);

  /* Open up requested dialog windows */
  ImodInfoWin->openSelectedWindows(windowKeys, modelViewOpen);

  // Set center and angles if appropriate
  if (sliceropen && setCenter && setAngles)
    setTopSlicerAngles(initAngles, &initCenter, false);
  if (sliceropen && setZoom)
    setTopSlicerZoom(initZoom, false);
    
  /* Start main application input loop. */
  if (Imod_debug)
    imodPuts("mainloop");
  imodPlugCall(&vi, 0, IMOD_REASON_STARTUP);

  nx = ImodPrefs->autoConAtStart();
  if (!vi.fakeImage && !vi.rgbStore && 
      (nx > 1 || (nx && (newModelCreated || (Model->flags & IMODF_NEW_TO_3DMOD)))))
    ImodInfoWin->setupAutoContrast();

  loopStarted = 1;
#ifdef Q_OS_MACX
  inputRaiseWindows();
#endif
  return qapp.exec();
}
Example #19
0
void scene::Init() {
    LoadModel();
    LoadView();
    LoadLight();
}
Example #20
0
/*
================
idClipModel::idClipModel
================
*/
idClipModel::idClipModel( const int renderModelHandle ) {
	Init();
	contents = CONTENTS_RENDERMODEL;
	LoadModel( renderModelHandle );
}
Example #21
0
ccsCOMPL_STAT wsf2ex1APPLICATION::Init(int argCount, char *arg[])
{
    wsf2libLOG_TRACE();
    ErrReset();


    // Turn off logging of warning on EXIT command
    evhTASK::LogExitWarning(FALSE);

    // Parses the command line arguments
    // and extract the configuration parameters
    // for ENV NAME, DB POINT and PROC NAME from the
    // command line or from the enviroment variables
    if (EvaluateArgs(argCount, arg, wsf2ex1DB_ROOT_POINT) == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_INIT, __FILE_LINE__, "wrong argument(s)");
	return FAILURE;
	}

    // Initialize CCS and connect to database
    if(InitCCS() == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_INIT, __FILE_LINE__, "cannot init CCS");
	return FAILURE;      
	}

    // Logs current startup configuration
    eccsLOG_1(("%s - Application started (proc name: %s, DB root point: %s)", 
	       GetProcName(), GetProcName(), GetDbRoot()));
    logData(wsf2ex1MOD,"%s - Application started (proc name: %s, DB root point: %s)", 
	    GetProcName(), GetProcName(), GetDbRoot());

   /*
    * Create factory for ACTIONS, DATA, CONFIG and CONTROL
    */
    wsf2libASSERT(mActionMgr == NULL);
    mActionMgr = new wsf2ex1ACTION_MGR(GetDbRoot(), argCount, arg, GetEventMgr());
    if (mActionMgr == NULL)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_FATAL, __FILE_LINE__, "no memory for allocating wsf2ex1ACTION_MGR");
	return FAILURE;
	}
    if (wsf2libHELPER::ObjectOk(mActionMgr, "ACTION_MGR") == ccsFALSE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_CREATE, __FILE_LINE__, "wsf2ex1ACTION_MGR");
	return FAILURE;	
	}

    /*
     * Set FSM context
     * TBD: rename method
     */
    SetControl(mActionMgr->GetControl());

    /*
     * Instantiate events and actions
     */
    if (CreateEvents(wsf2ex1EVENTS_FILENAME) == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_CREATE, __FILE_LINE__, "Events");
	return FAILURE;	
	}
    if (mActionMgr->CreateActions() == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_CREATE, __FILE_LINE__, "Actions");
	return FAILURE;	
	}
    /*
     * Load SCXML Model
     */
    if (LoadModel(wsf2ex1MODEL_FILENAME, mActionMgr->SCXMLGetActions(), mActionMgr->SCXMLGetActivities()) == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_FATAL, __FILE_LINE__, "cannot load SCXML model");
	return FAILURE;
	}

    /*
     * Initialize all events and actions and data structures
     */
    if (mActionMgr->Init() == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_FATAL, __FILE_LINE__, "initializing actions and data structures");
	return FAILURE;
	}

    /*
     * Start the execution of SCXML model
     */
    if (StartModel() == FAILURE)
	{
	errAdd(wsf2ex1MOD, wsf2ex1ERR_FATAL, __FILE_LINE__, "cannot start SCXML model execution");
	return FAILURE;
	}

    return SUCCESS;
} 
bool StudioModel::PostLoadModel( char *modelname )
{
	// preload textures
	if (m_pstudiohdr->numtextures == 0)
	{
		char texturename[256];

		strcpy( texturename, modelname );
		strcpy( &texturename[strlen(texturename) - 4], "T.mdl" );

		m_ptexturehdr = LoadModel( texturename );
		if (!m_ptexturehdr)
		{
			FreeModel ();
			return false;
		}
		m_owntexmodel = true;
	}
	else
	{
		m_ptexturehdr = m_pstudiohdr;
		m_owntexmodel = false;
	}

	// preload animations
	if (m_pstudiohdr->numseqgroups > 1)
	{
		for (int i = 1; i < m_pstudiohdr->numseqgroups; i++)
		{
			char seqgroupname[256];

			strcpy( seqgroupname, modelname );
			sprintf( &seqgroupname[strlen(seqgroupname) - 4], "%02d.mdl", i );

			m_panimhdr[i] = LoadModel( seqgroupname );
			if (!m_panimhdr[i])
			{
				FreeModel ();
				return false;
			}
		}
	}

	SetSequence (0);
	SetController (0, 0.0f);
	SetController (1, 0.0f);
	SetController (2, 0.0f);
	SetController (3, 0.0f);
	SetMouth (0.0f);

	int n;
	for (n = 0; n < m_pstudiohdr->numbodyparts; n++)
		SetBodygroup (n, 0);

	SetSkin (0);
/*
	vec3_t mins, maxs;
	ExtractBbox (mins, maxs);
	if (mins[2] < 5.0f)
		m_origin[2] = -mins[2];
*/
	return true;
}
Example #23
0
static void PopulateTraceNodes(void)
{
	int             i, m, frame, castShadows;
	float           temp;
	entity_t       *e;
	const char     *value;
	picoModel_t    *model;
	vec3_t          origin, scale, angles;
	matrix_t        rotation;
	matrix_t        transform;


	/* add worldspawn triangles */
	MatrixIdentity(transform);
	PopulateWithBSPModel(&bspModels[0], transform);

	/* walk each entity list */
	for(i = 1; i < numEntities; i++)
	{
		/* get entity */
		e = &entities[i];

		/* get shadow flags */
		castShadows = ENTITY_CAST_SHADOWS;
		GetEntityShadowFlags(e, NULL, &castShadows, NULL);

		/* early out? */
		if(!castShadows)
			continue;

		/* get entity origin */
		GetVectorForKey(e, "origin", origin);

		/* get "angle" (yaw) or "angles" (pitch yaw roll) */
		MatrixIdentity(rotation);
		angles[0] = angles[1] = angles[2] = 0.0f;

		value = ValueForKey(e, "angle");
		if(value[0] != '\0')
		{
			angles[1] = atof(value);
			MatrixFromAngles(rotation, angles[PITCH], angles[YAW], angles[ROLL]);
		}

		value = ValueForKey(e, "angles");
		if(value[0] != '\0')
		{
			sscanf(value, "%f %f %f", &angles[0], &angles[1], &angles[2]);
			MatrixFromAngles(rotation, angles[PITCH], angles[YAW], angles[ROLL]);
		}

		value = ValueForKey(e, "rotation");
		if(value[0] != '\0')
		{
			sscanf(value, "%f %f %f %f %f %f %f %f %f", &rotation[0], &rotation[1], &rotation[2],
				   &rotation[4], &rotation[5], &rotation[6], &rotation[8], &rotation[9], &rotation[10]);
		}

		/* get scale */
		scale[0] = scale[1] = scale[2] = 1.0f;
		temp = FloatForKey(e, "modelscale");
		if(temp != 0.0f)
			scale[0] = scale[1] = scale[2] = temp;
		value = ValueForKey(e, "modelscale_vec");
		if(value[0] != '\0')
			sscanf(value, "%f %f %f", &scale[0], &scale[1], &scale[2]);

		MatrixMultiplyScale(rotation, scale[0], scale[1], scale[2]);

		/* set transform matrix */
		MatrixIdentity(transform);
		MatrixSetupTransformFromRotation(transform, rotation, origin);

		//% m4x4_pivoted_transform_by_vec3(transform, origin, angles, eXYZ, scale, vec3_origin);

		/* get model */
		value = ValueForKey(e, "model");

		/* switch on model type */
		switch (value[0])
		{
				/* no model */
			case '\0':
				break;

				/* bsp model */
			case '*':
				m = atoi(&value[1]);
				if(m <= 0 || m >= numBSPModels)
					continue;
				PopulateWithBSPModel(&bspModels[m], transform);
				break;

				/* external model */
			default:
				frame = IntForKey(e, "_frame");
				model = LoadModel((char *)value, frame);
				if(model == NULL)
					continue;
				PopulateWithPicoModel(castShadows, model, transform);
				continue;
		}

		/* get model2 */
		value = ValueForKey(e, "model2");

		/* switch on model type */
		switch (value[0])
		{
				/* no model */
			case '\0':
				break;

				/* bsp model */
			case '*':
				m = atoi(&value[1]);
				if(m <= 0 || m >= numBSPModels)
					continue;
				PopulateWithBSPModel(&bspModels[m], transform);
				break;

				/* external model */
			default:
				frame = IntForKey(e, "_frame2");
				model = LoadModel((char *)value, frame);
				if(model == NULL)
					continue;
				PopulateWithPicoModel(castShadows, model, transform);
				continue;
		}
	}
}
Example #24
0
 void Panel::setModel(FileSource* mod_fs, const std::string& path)
 {
   setModel(LoadModel(mod_fs, getShaders(), path, getDevice()));
 }
Example #25
0
void Model::LoadModelFromFile(GLchar* path)
{
	LoadModel(path);
}
Example #26
0
/*
================
idClipModel::idClipModel
================
*/
idClipModel::idClipModel( const char *name ) {
	Init();
	LoadModel( name );
}
Example #27
0
/*
================
idClipModel::idClipModel
================
*/
idClipModel::idClipModel( const idTraceModel &trm ) {
	Init();
	LoadModel( trm );
}
Example #28
0
int main(int argc, char *argv[]) {
  char train_file_name[256];
  char test_file_name[256];
  char output_file_name[256];
  char model_file_name[256];
  struct Problem *train, *test;
  struct Model *model;
  int num_correct = 0, num_empty = 0, num_multi = 0, num_incl = 0;
  double avg_conf = 0, avg_cred = 0;
  const char *error_message;

  ParseCommandLine(argc, argv, train_file_name, test_file_name, output_file_name, model_file_name);
  error_message = CheckParameter(&param);

  if (error_message != NULL) {
    std::cerr << error_message << std::endl;
    exit(EXIT_FAILURE);
  }

  train = ReadProblem(train_file_name);
  test = ReadProblem(test_file_name);

  std::ofstream output_file(output_file_name);
  if (!output_file.is_open()) {
    std::cerr << "Unable to open output file: " << output_file_name << std::endl;
    exit(EXIT_FAILURE);
  }

  std::chrono::time_point<std::chrono::steady_clock> start_time = std::chrono::high_resolution_clock::now();

  if (param.load_model == 1) {
    model = LoadModel(model_file_name);
    if (model == NULL) {
      exit(EXIT_FAILURE);
    }
  } else {
    model = TrainCP(train, &param);
  }

  if (param.save_model == 1) {
    if (SaveModel(model_file_name, model) != 0) {
      std::cerr << "Unable to save model file" << std::endl;
    }
  }

  for (int i = 0; i < test->num_ex; ++i) {
    double conf, cred;
    std::vector<int> predict_label;

    predict_label = PredictCP(train, model, test->x[i], conf, cred);

    avg_conf += conf;
    avg_cred += cred;

    output_file << std::resetiosflags(std::ios::fixed) << test->y[i] << ' ' << predict_label[0] << ' '
                << std::setiosflags(std::ios::fixed) << conf << ' ' << cred;
    if (predict_label[0] == test->y[i]) {
      ++num_correct;
    }

    if (predict_label.size() == 1) {
      ++num_empty;
      output_file << " Empty\n";
    } else {
      output_file << " set:";
      for (size_t j = 1; j < predict_label.size(); ++j) {
        output_file << ' ' << predict_label[j];
        if (predict_label[j] == test->y[i]) {
          ++num_incl;
        }
      }
      if (predict_label.size() > 2) {
        ++num_multi;
        output_file << " Multi\n";
      } else {
        output_file << " Single\n";
      }
    }
    std::vector<int>().swap(predict_label);
  }
  avg_conf /= test->num_ex;
  avg_cred /= test->num_ex;

  std::chrono::time_point<std::chrono::steady_clock> end_time = std::chrono::high_resolution_clock::now();

  std::cout << "Simple Accuracy: " << 100.0*num_correct/test->num_ex << '%'
            << " (" << num_correct << '/' << test->num_ex << ") "
            << "Mean Confidence: " << std::fixed << std::setprecision(4) << 100*avg_conf << "%, "
            << "Mean Credibility: " << 100*avg_cred << "%\n";
  std::cout << "Accuracy: " << 100.0*num_incl/test->num_ex << '%'
            << " (" << num_incl << '/' << test->num_ex << ") "
            << "Multi Prediction: " << std::fixed << std::setprecision(4) << 100.0*num_multi/test->num_ex << "%, "
            << "Empty Prediction: " << 100.0*num_empty/test->num_ex << "%\n";
  output_file.close();

  std::cout << "Time cost: " << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count()/1000.0 << " s\n";

  FreeProblem(train);
  FreeProblem(test);
  FreeModel(model);
  FreeParam(&param);

  return 0;
}
Example #29
0
/*
====================
idRenderModelMD5::InstantiateDynamicModel
====================
*/
idRenderModel *idRenderModelMD5::InstantiateDynamicModel( const struct renderEntity_s *ent, const struct viewDef_s *view, idRenderModel *cachedModel ) {
	int					i, surfaceNum;
	idMD5Mesh			*mesh;
	idRenderModelStatic	*staticModel;

	if ( cachedModel && !r_useCachedDynamicModels.GetBool() ) {
		delete cachedModel;
		cachedModel = NULL;
	}

	if ( purged ) {
		common->DWarning( "model %s instantiated while purged", Name() );
		LoadModel();
	}

	if ( !ent->joints ) {
		common->Printf( "idRenderModelMD5::InstantiateDynamicModel: NULL joints on renderEntity for '%s'\n", Name() );
		delete cachedModel;
		return NULL;
	} else if ( ent->numJoints != joints.Num() ) {
		common->Printf( "idRenderModelMD5::InstantiateDynamicModel: renderEntity has different number of joints than model for '%s'\n", Name() );
		delete cachedModel;
		return NULL;
	}

	tr.pc.c_generateMd5++;

	if ( cachedModel ) {
		assert( dynamic_cast<idRenderModelStatic *>(cachedModel) != NULL );
		assert( idStr::Icmp( cachedModel->Name(), MD5_SnapshotName ) == 0 );
		staticModel = static_cast<idRenderModelStatic *>(cachedModel);
	} else {
		staticModel = new idRenderModelStatic;
		staticModel->InitEmpty( MD5_SnapshotName );
	}

	staticModel->bounds.Clear();

	if ( r_showSkel.GetInteger() ) {
		if ( ( view != NULL ) && ( !r_skipSuppress.GetBool() || !ent->suppressSurfaceInViewID || ( ent->suppressSurfaceInViewID != view->renderView.viewID ) ) ) {
			// only draw the skeleton
			DrawJoints( ent, view );
		}

		if ( r_showSkel.GetInteger() > 1 ) {
			// turn off the model when showing the skeleton
			staticModel->InitEmpty( MD5_SnapshotName );
			return staticModel;
		}
	}

	// create all the surfaces
	for( mesh = meshes.Ptr(), i = 0; i < meshes.Num(); i++, mesh++ ) {
		// avoid deforming the surface if it will be a nodraw due to a skin remapping
		// FIXME: may have to still deform clipping hulls
		const idMaterial *shader = mesh->shader;
		
		shader = R_RemapShaderBySkin( shader, ent->customSkin, ent->customShader );
		
		if ( !shader || ( !shader->IsDrawn() && !shader->SurfaceCastsShadow() ) ) {
			staticModel->DeleteSurfaceWithId( i );
			mesh->surfaceNum = -1;
			continue;
		}

		modelSurface_t *surf;

		if ( staticModel->FindSurfaceWithId( i, surfaceNum ) ) {
			mesh->surfaceNum = surfaceNum;
			surf = &staticModel->surfaces[surfaceNum];
		} else {

			// Remove Overlays before adding new surfaces
			idRenderModelOverlay::RemoveOverlaySurfacesFromModel( staticModel );

			mesh->surfaceNum = staticModel->NumSurfaces();
			surf = &staticModel->surfaces.Alloc();
			surf->geometry = NULL;
			surf->shader = NULL;
			surf->id = i;
		}

		mesh->UpdateSurface( ent, ent->joints, surf );

		staticModel->bounds.AddPoint( surf->geometry->bounds[0] );
		staticModel->bounds.AddPoint( surf->geometry->bounds[1] );
	}

	return staticModel;
}
Example #30
0
void init(void)
{
    dumpInfo();

    m = LoadModel("bunnyplus.obj");

    // GL inits
    glClearColor(0.0,0.3,0.3,0);
    glEnable(GL_DEPTH_TEST);
    printError("GL inits");

    // Load and compile shader
    program = loadShaders("lab2-4.vert", "lab2-4.frag");
    printError("init shader");

    // Load texture
    LoadTGATextureSimple("grass.tga", &myTex);

    // Upload geometry to the GPU:

    // Allocate and activate Vertex Array Object
    glGenVertexArrays(1, &bunnyVertexArrayObjID);
    glGenBuffers(1, &bunnyVertexBufferObjID);
    glGenBuffers(1, &bunnyIndexBufferObjID);
    //glGenBuffers(1, &bunnyNormalBufferObjID);
    glGenBuffers(1, &bunnyTexCoordBufferObjID);

    glBindVertexArray(bunnyVertexArrayObjID);

    // VBO for vertex data
    glBindBuffer(GL_ARRAY_BUFFER, bunnyVertexBufferObjID);
    glBufferData(GL_ARRAY_BUFFER, m->numVertices*3*sizeof(GLfloat), m->vertexArray, GL_STATIC_DRAW);
    glVertexAttribPointer(glGetAttribLocation(program, "inPosition"), 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(glGetAttribLocation(program, "inPosition"));

    printError("init vertex data");

    // VBO for normal data
    /*
    glBindBuffer(GL_ARRAY_BUFFER, bunnyNormalBufferObjID);
    glBufferData(GL_ARRAY_BUFFER, m->numVertices*3*sizeof(GLfloat), m->normalArray, GL_STATIC_DRAW);
    glVertexAttribPointer(glGetAttribLocation(program, "inNormal"), 3, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(glGetAttribLocation(program, "inNormal"));

    printError("init normal data");
           */

    if (m->texCoordArray != NULL)
    {
        glBindBuffer(GL_ARRAY_BUFFER, bunnyTexCoordBufferObjID);
        glBufferData(GL_ARRAY_BUFFER, m->numVertices*2*sizeof(GLfloat), m->texCoordArray, GL_STATIC_DRAW);
        glVertexAttribPointer(glGetAttribLocation(program, "inTexCoord"), 2, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(glGetAttribLocation(program, "inTexCoord"));

        printError("init texture data");
    }

    // Active texture object
    glBindTexture(GL_TEXTURE_2D, myTex);


    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bunnyIndexBufferObjID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, m->numIndices*sizeof(GLuint), m->indexArray, GL_STATIC_DRAW);

    // End of upload of geometry

    printError("init arrays");
}