Exemple #1
0
	//------------------------------------------------------------------------
	Engine::~Engine()
	{
        stopEngine();

		// remove default scripting methods
		DefaultScriptingFunctions::delMethods();

		// remove the manager
		delete _resmgr;

		// delete the clock
		delete _clock;

		// delete the kernel
		delete _kernel;

		// delete the scripting engine
		delete _script;

		// delete the event system
		delete _event;

		// remove property manager
		delete _propmgr;

		// remove profiler
		delete _profiler;

		// delete the log system
		delete _logger;

	}
Exemple #2
0
void AnalysisWidget::engineError(QProcess::ProcessError e)
{
    MessageDialog::warning(tr("There was an error (%1) running engine <b>%2</b>.")
                           .arg(e)
                           .arg(ui.engineList->currentText()));
    stopEngine();
}
Exemple #3
0
void AnalysisWidget::startEngine()
{
    int index = ui.engineList->currentIndex();
    stopEngine();
    if(index != -1)
    {
        if(parentWidget() && !parentWidget()->isVisible())
        {
            parentWidget()->show();
        }
        ui.variationText->clear();
        m_engine = Engine::newEngine(index);
        ui.vpcount->setEnabled(m_engine->providesMvp());
        ui.label->setEnabled(m_engine->providesMvp());
        if(!m_engine->providesMvp())
        {
            ui.vpcount->setValue(1);
        }

        connect(m_engine, SIGNAL(activated()), SLOT(engineActivated()));
        connect(m_engine, SIGNAL(error(QProcess::ProcessError)), SLOT(engineError(QProcess::ProcessError)));
        connect(m_engine, SIGNAL(deactivated()), SLOT(engineDeactivated()));
        connect(m_engine, SIGNAL(analysisUpdated(const Analysis&)),
                SLOT(showAnalysis(const Analysis&)));
        m_engine->setMoveTime(m_moveTime);
        m_engine->activate();
        QString key = QString("/") + objectName() + "/Engine";
        AppSettings->setValue(key, ui.engineList->itemText(index));
    }
}
Exemple #4
0
void AnalysisWidget::slotReconfigure()
{
    QString oldEngineName = ui.engineList->currentText();
    if(oldEngineName.isEmpty())
    {
        QString key = QString("/") + objectName() + "/Engine";
        oldEngineName = AppSettings->value(key).toString();
    }

    EngineList enginesList;
    enginesList.restore();
    QStringList names = enginesList.names();
    ui.engineList->clear();
    ui.engineList->insertItems(0,	names);
    int index = names.indexOf(oldEngineName);
    if(index != -1)
    {
        ui.engineList->setCurrentIndex(index);
    }
    else
    {
        ui.engineList->setCurrentIndex(0);
        stopEngine();
    }

    int fontSize = AppSettings->getValue("/General/ListFontSize").toInt();
    QFont f = ui.variationText->font();
    f.setPointSize(fontSize);
    setFont(f);
    ui.variationText->setFont(f);
}
Exemple #5
0
void AnalysisWidget::slotVisibilityChanged(bool visible)
{
    if(isEngineRunning() && !visible && !parentWidget()->isVisible())
    {
        stopEngine();
    }
}
Exemple #6
0
void MainWindow::startScript(){
    Logger::getInstance().log("lets run the SSM, registering the SMEngine" ,loglevel);
    if (startAgent->isChecked()){
        Logger::getInstance().log("Gonna to start a QProcess with the Agent now", loglevel);
    }

    vinceAdapter = new VinceAdapter();
    smEngine = new SMEngine(document, utteranceDocument);
    smEngine->setObjectName("smEngine");
    stateMachine->registerObject(smEngine);
    QTimer timer;
    timer.start(2000);
    this->hide();

    QObject::connect(smEngine, SIGNAL(executeMurml(QString)), vinceAdapter, SLOT(executeMurml(QString)));
    QObject::connect(this, SIGNAL(firstUse(bool)), smEngine, SLOT(toggleFirstUse(bool)));
    QObject::connect(stateMachine, SIGNAL(finished()), smEngine, SLOT(finished()));
    QObject::connect(smEngine, SIGNAL(stopEngine()), this, SLOT(showGui()));
    stateMachine->start();
    if (firstUseBox->isChecked())
        emit firstUse(true);
    smEngine->startEngine();
    Logger::getInstance().log("StateMachine started", loglevel);

}
Exemple #7
0
int BulkController::close() {
    if (!isOpen()) {
        qDebug() << " device" << getName() << "already closed";
        return -1;
    }

    qDebug() << "Shutting down USB Bulk device" << getName();

    // Stop the reading thread
    if (m_pReader == NULL) {
        qWarning() << "BulkReader not present for" << getName()
                   << "yet the device is open!";
    } else {
        disconnect(m_pReader, SIGNAL(incomingData(QByteArray, mixxx::Duration)),
                   this, SLOT(receive(QByteArray, mixxx::Duration)));
        m_pReader->stop();
        controllerDebug("  Waiting on reader to finish");
        m_pReader->wait();
        delete m_pReader;
        m_pReader = NULL;
    }

    // Stop controller engine here to ensure it's done before the device is
    // closed incase it has any final parting messages
    stopEngine();

    // Close device
    controllerDebug("  Closing device");
    libusb_close(m_phandle);
    m_phandle = NULL;
    setOpen(false);
    return 0;
}
Exemple #8
0
int HidController::close() {
    if (!isOpen()) {
        qDebug() << "HID device" << getName() << "already closed";
        return -1;
    }

    qDebug() << "Shutting down HID device" << getName();

    // Stop the reading thread
    if (m_pReader == NULL) {
        qWarning() << "HidReader not present for" << getName()
                   << "yet the device is open!";
    } else {
        disconnect(m_pReader, SIGNAL(incomingData(QByteArray)),
                   this, SLOT(receive(QByteArray)));
        m_pReader->stop();
        hid_set_nonblocking(m_pHidDevice, 1);   // Quit blocking
        if (debugging()) qDebug() << "  Waiting on reader to finish";
        m_pReader->wait();
        delete m_pReader;
        m_pReader = NULL;
    }

    // Stop controller engine here to ensure it's done before the device is closed
    //  incase it has any final parting messages
    stopEngine();

    // Close device
    if (debugging()) {
        qDebug() << "  Closing device";
    }
    hid_close(m_pHidDevice);
    setOpen(false);
    return 0;
}
RunControl::StopResult AnalyzerRunControl::stop()
{
    if (!m_isRunning)
        return StoppedSynchronously;

    stopEngine();
    m_isRunning = false;
    return AsynchronousStop;
}
Exemple #10
0
/*!
  \internal
  If the ship has any braking force available, release the
  brakes, ie stop applying the breaks. Also, if the ship is
  braking, stop the ship movement, and stop its rotation. I
  don't know if this is actually correct, but this is how it
  was programmed when I ported it to Qtopia 4.2.
 */
void KShip::stopBraking()
{
    if (brakeForce()) {
        if (isBraking()) {
            stopEngine();
	    stopRotation();
        }
        releaseBrakes();
    }
}
Exemple #11
0
void CameraEngine::updateCamera(const int &camera)
{
    stopEngine();
    wait(1000);
    QSettings settings("RobotStation");
    settings.setValue("camera",camera);
    m_camera = camera;
    qDebug() << "camera changed to " << camera;
    startEngine();
}
Exemple #12
0
/*!
  Reduce the ship's power level by \a delta, which should be
  a positive number. If the reduction makes the power level
  negative, reset it to 0; If the ship's power level becomes
  0, set the shield strength to 0, but don't drop the shiled
  here if it is up. The shiled is only dropped in phase 1 of
  the scene animation.
  \internal
 */
void KShip::reducePowerLevel(int delta)
{
    powerLevel_ -= delta;
    if (powerLevel_ < 0) {
	powerLevel_ = 0;
        stopEngine();
	shield()->setStrength(0);
    }
    view_->markVitalsChanged();
}
void GPG_Application::exitEngine()
{
	// We only want to kill the engine if it has been initialized
	if (!m_engineInitialized)
		return;

	sound_exit();
	if (m_ketsjiengine)
	{
		stopEngine();
		delete m_ketsjiengine;
		m_ketsjiengine = 0;
	}
	if (m_kxsystem)
	{
		delete m_kxsystem;
		m_kxsystem = 0;
	}
	if (m_networkdevice)
	{
		delete m_networkdevice;
		m_networkdevice = 0;
	}
	if (m_mouse)
	{
		delete m_mouse;
		m_mouse = 0;
	}
	if (m_keyboard)
	{
		delete m_keyboard;
		m_keyboard = 0;
	}
	if (m_rasterizer)
	{
		delete m_rasterizer;
		m_rasterizer = 0;
	}
	if (m_rendertools)
	{
		delete m_rendertools;
		m_rendertools = 0;
	}
	if (m_canvas)
	{
		delete m_canvas;
		m_canvas = 0;
	}

	GPU_extensions_exit();

	m_exitRequested = 0;
	m_engineInitialized = false;
}
Exemple #14
0
void AnalysisWidget::toggleAnalysis()
{
    if(!isAnalysisEnabled())
    {
        stopEngine();
    }
    else
    {
        startEngine();
    }
}
Exemple #15
0
void Engine::checkShutdown() {
#if EFI_MAIN_RELAY_CONTROL || defined(__DOXYGEN__)
	int rpm = rpmCalculator.getRpm();

	const float vBattThreshold = 5.0f;
	if (isValidRpm(rpm) && sensors.vBatt < vBattThreshold && stopEngineRequestTimeNt == 0) {
		stopEngine();
		// todo: add stepper motor parking
	}
#endif /* EFI_MAIN_RELAY_CONTROL */
}
void GPG_Application::exitEngine()
{
	// We only want to kill the engine if it has been initialized
	if (!m_engineInitialized)
		return;

	sound_exit();
	if (m_ketsjiengine)
	{
		stopEngine();
		delete m_ketsjiengine;
		m_ketsjiengine = 0;
	}
	if (m_kxsystem)
	{
		delete m_kxsystem;
		m_kxsystem = 0;
	}
	if (m_networkdevice)
	{
		delete m_networkdevice;
		m_networkdevice = 0;
	}
	if (m_mouse)
	{
		delete m_mouse;
		m_mouse = 0;
	}
	if (m_keyboard)
	{
		delete m_keyboard;
		m_keyboard = 0;
	}
	if (m_rasterizer)
	{
		delete m_rasterizer;
		m_rasterizer = 0;
	}
	if (m_canvas)
	{
		delete m_canvas;
		m_canvas = 0;
	}

	GPU_extensions_exit();

#ifdef WITH_PYTHON
	// Call this after we're sure nothing needs Python anymore (e.g., destructors)
	exitGamePlayerPythonScripting();
#endif

	m_exitRequested = 0;
	m_engineInitialized = false;
}
void ApplicationPlugin::startEngine()
{
    stopEngine();

    auto& stngs = iscore::GUIApplicationContextPlugin::context.settings<Audio::Settings::Model>();
    auto api = stngs.getDriverId();
    if(api == -1)
        return;

    // Initialize libaudiostream structures
    auto card = CardIdFromString(api, stngs.getCard());
    if(card == -1)
        return;

    GetDeviceInfo(api, card, &m_ctx.device_info);
    auto& dev = m_ctx.device_info;
    qDebug() << dev.fName
             << dev.fMaxInputChannels
             << dev.fMaxOutputChannels
             << dev.fDefaultBufferSize
             << dev.fDefaultSampleRate;

    qDebug() << "openign with" << stngs.getRate() << stngs.getBufferSize();
    AudioGlobalsInit(2, 2, stngs.getRate(),
                     stngs.getBufferSize(),
                     65536*4,
                     0,
                     1);

    m_ctx.renderer = MakeAudioRenderer(api);
    m_ctx.sample_rate = stngs.getRate();
    GetAudioRendererInfo(m_ctx.renderer, &m_ctx.renderer_info);
    OpenAudioRenderer(m_ctx.renderer, card, card, 2, 2, stngs.getBufferSize(), stngs.getRate());

    emit audioEngineRestarted();
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	static UINT msgs[] = {BB_RECONFIGURE, BB_REDRAWGUI, BB_BROADCAST, 0};

	switch (message)
	{

	default:
		return DefWindowProc (hwnd, message, wParam, lParam);

	case WM_CREATE:
		m_hwnd = hwnd;
		SendMessage(BBhwnd, BB_REGISTERMESSAGE, (WPARAM)hwnd, (LPARAM)msgs);
		break;

	case WM_DESTROY:
		SendMessage(BBhwnd, BB_UNREGISTERMESSAGE, (WPARAM)hwnd, (LPARAM)msgs);
		break;

	case BB_BROADCAST:
		if (0 == memicmp((LPCSTR)lParam, "@BBLeanSkin.", 12))
		{
			const char *msg = (LPCSTR)lParam + 12;
			if (0 == stricmp(msg, "About"))
				about_box();
			else
				if (0 == stricmp(msg, "toggleLog"))
					goto toggle_log;
				else
					if (0 == stricmp(msg, "toggleSkin"))
					{
						if (engine_running)
						{
							write_log("\r\n\t---- stopping engine ----\r\n");
							PostMessage(hwnd, bbSkinMsg, MSGID_UNLOAD, 0);
							PostMessage(hwnd, BB_QUIT, 0, 0);
						}
						else
						{
							write_log("\r\n\t---- starting engine ----\r\n");
							startEngine();
						}
					}
		}
		break;

	case BB_QUIT:
		stopEngine();
		break;

	case BB_RECONFIGURE:
		if (is_plugin) // i.e. not loaded by BBWinSkin
			reconfigureEngine();
		break;

toggle_log:
		WriteBool(rcpath, "bbleanskin.option.enableLog:", false == enableLog);
		reconfigureEngine();
		break;

		//====================
		// used in combination with bbstylemaker to update the skin info
		// and optionally force active or button pressed state.

	case BB_REDRAWGUI:
		if (BBRG_WINDOW & wParam)
		{
			if (wParam & BBRG_STICKY)
			{   // and to transfer the is_sticky info from bb.
				PostMessage((HWND)lParam, bbSkinMsg, MSGID_BB_SETSTICKY, 0 != (wParam & BBRG_FOCUS));
				break;
			}

			static bool prev_opt;
			int opt = 0;
			if (prev_opt)               opt = MSGID_BBSM_RESET;
			if (wParam & BBRG_FOCUS)    opt = MSGID_BBSM_SETACTIVE;
			if (wParam & BBRG_PRESSED)  opt = MSGID_BBSM_SETPRESSED;
			prev_opt = opt >= MSGID_BBSM_SETACTIVE;

			if (opt) setEngineOption(opt);
			refreshStyle();
		}
		break;

		//====================
		// Log string sent by the engine dll

	case WM_COPYDATA:
	{
		if (201 == ((PCOPYDATASTRUCT)lParam)->dwData)
		{
			write_log((char*)((COPYDATASTRUCT*)lParam)->lpData);
			return TRUE;
		}
		break;
	}

	//====================
	// things for the Log EDIT control

	case WM_SETFOCUS:
		if (hwndLog) SetFocus(hwndLog);
		break;

	case WM_SIZE:
		if (hwndLog) MoveWindow(hwndLog, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE);
		break;

	case WM_CLOSE:
		if (hwndLog) goto toggle_log;
		break;
	}
	return 0 ;
}
Exemple #19
0
AnalysisWidget::~AnalysisWidget()
{
    stopEngine();
    delete m_tablebase;
}
extern "C" BOOL WINAPI DllMain(HINSTANCE hi, DWORD reason, LPVOID reserved)
{
	if (reason==DLL_PROCESS_ATTACH)
	{
		hInstance = hi;
		WNDCLASS wc;
		RECT dt;

		if (BBhwnd)
		{
			MessageBox(BBhwnd, "Dont load me twice!", szAppName, MB_OK|MB_SETFOREGROUND);
			return FALSE;
		}

		const char *bbv = GetBBVersion();
		if (0 == memicmp(bbv, "bblean", 6)) BBVersion = 2;
		else
			if (0 == memicmp(bbv, "bb", 2)) BBVersion = 1;
			else BBVersion = 0;

		BBhwnd = GetBBWnd();
		set_my_path(rcpath, "bbLeanSkin.rc");

		ZeroMemory(&wc, sizeof(wc));
		wc.lpszClassName = szAppName;
		wc.hInstance = hInstance;
		wc.lpfnWndProc = WndProc;

		// ##### COMMENTED OUT DUE TO COMPATIBILITY REASONS #####
		// ###### -> WAS THIS CHECK USED TO DETECT BBLEAN? ######
		// if (NULL == GetSettingPtr(SN_WINUNFOCUS_TITLE))
		//	return FALSE;
		// ######################################################

		if (FindWindow(wc.lpszClassName, NULL) || FALSE == RegisterClass(&wc))
			return FALSE;

		// center the window
		SystemParametersInfo(SPI_GETWORKAREA, 0, &dt, 0);
		int width = 480;
		int height = 300;
		int xleft = (dt.left+dt.right-width)/2;
		int ytop = (dt.top+dt.bottom-height)/2;

		CreateWindow(
			wc.lpszClassName,
			"bbLeanSkin Log",
			//WS_OVERLAPPEDWINDOW,
			WS_POPUP|WS_CAPTION|WS_SIZEBOX|WS_SYSMENU|WS_MAXIMIZEBOX|WS_MINIMIZEBOX,
			xleft, ytop, width, height,
			NULL,
			NULL,
			wc.hInstance,
			NULL
		);
	}
	else
		if (reason==DLL_PROCESS_DETACH)
		{
			stopEngine();
			DestroyWindow(m_hwnd);
			UnregisterClass(szAppName, hInstance);
		}
	return TRUE;
}
void endPlugin(HINSTANCE hMainInstance)
{
	stopEngine();
	is_plugin = false;
}
bool GPG_Application::startEngine(void)
{
	if (m_engineRunning) {
		return false;
	}
	
	// Temporary hack to disable banner display for NaN approved content.
	/*
	m_canvas->SetBannerDisplayEnabled(true);
	Camera* cam;
	cam = (Camera*)scene->camera->data;
	if (cam) {
	if (((cam->flag) & 48)==48) {
	m_canvas->SetBannerDisplayEnabled(false);
	}
	}
	else {
	showError(CString("Camera data invalid."));
	return false;
	}
	*/
	
	// create a scene converter, create and convert the stratingscene
	m_sceneconverter = new KX_BlenderSceneConverter(m_maggie, m_ketsjiengine);
	if (m_sceneconverter)
	{
		STR_String startscenename = m_startSceneName.Ptr();
		m_ketsjiengine->SetSceneConverter(m_sceneconverter);

		//	if (always_use_expand_framing)
		//		sceneconverter->SetAlwaysUseExpandFraming(true);
		if (m_blendermat)
			m_sceneconverter->SetMaterials(true);
		if (m_blenderglslmat && (m_globalSettings->matmode == GAME_MAT_GLSL))
			m_sceneconverter->SetGLSLMaterials(true);
		if (m_startScene->gm.flag & GAME_NO_MATERIAL_CACHING)
			m_sceneconverter->SetCacheMaterials(false);

		KX_Scene* startscene = new KX_Scene(m_keyboard,
			m_mouse,
			m_networkdevice,
			startscenename,
			m_startScene,
			m_canvas);
		
#ifdef WITH_PYTHON
			// some python things
			PyObject *gameLogic, *gameLogic_keys;
			setupGamePython(m_ketsjiengine, startscene, m_maggie, NULL, &gameLogic, &gameLogic_keys, m_argc, m_argv);
#endif // WITH_PYTHON

		//initialize Dome Settings
		if (m_startScene->gm.stereoflag == STEREO_DOME)
			m_ketsjiengine->InitDome(m_startScene->gm.dome.res, m_startScene->gm.dome.mode, m_startScene->gm.dome.angle, m_startScene->gm.dome.resbuf, m_startScene->gm.dome.tilt, m_startScene->gm.dome.warptext);

		// initialize 3D Audio Settings
		AUD_I3DDevice* dev = AUD_get3DDevice();
		if (dev)
		{
			dev->setSpeedOfSound(m_startScene->audio.speed_of_sound);
			dev->setDopplerFactor(m_startScene->audio.doppler_factor);
			dev->setDistanceModel(AUD_DistanceModel(m_startScene->audio.distance_model));
		}

#ifdef WITH_PYTHON
		// Set the GameLogic.globalDict from marshal'd data, so we can
		// load new blend files and keep data in GameLogic.globalDict
		loadGamePythonConfig(m_pyGlobalDictString, m_pyGlobalDictString_Length);
#endif
		m_sceneconverter->ConvertScene(
			startscene,
			m_rasterizer,
			m_canvas);
		m_ketsjiengine->AddScene(startscene);
		
		// Create a timer that is used to kick the engine
		if (!m_frameTimer) {
			m_frameTimer = m_system->installTimer(0, kTimerFreq, frameTimerProc, m_mainWindow);
		}
		m_rasterizer->Init();
		m_ketsjiengine->StartEngine(true);
		m_engineRunning = true;
		
		// Set the animation playback rate for ipo's and actions
		// the framerate below should patch with FPS macro defined in blendef.h
		// Could be in StartEngine set the framerate, we need the scene to do this
		Scene *scene= startscene->GetBlenderScene(); // needed for macro
		m_ketsjiengine->SetAnimFrameRate(FPS);
	}
	
	if (!m_engineRunning)
	{
		stopEngine();
	}
	
	return m_engineRunning;
}
ApplicationPlugin::~ApplicationPlugin()
{
    stopEngine();
    //stopMTDSPFactories();
}
Exemple #24
0
/*!
  The advance function does quite a lot for the ship sprite.
  In \a phase 0, if the ship is marked dead, just return. If
  not, move the ship using its current position and velocity.
  Then get the list of all collisions with the ship and run
  through the list.

  If the ship collides with a rock, then if the shield is
  up, destroy the rock. If the shiled is down (normal), mark
  the ship dead and return.

  If the ship collides with a powerup, then if the shield is
  up, mark the powerup destroyed. If the shield is not up,
  apply the powerup to the ship.

  In phase 1, if the ship is marked dead, explode the ship,
  delete it, and return. Otherwise, handle ship rotation,
  breaking, ship velocity, an teleporting. also update the
  image if the ship is rotating, and the exhaust image, if
  the engine is on. If the shiled is up, handle its image
  and age. Finally, in phase one, handle the firing of the
  missiles.
  \internal
 */
void KShip::advance(int phase)
{
    if (phase == 0) {
	if (dying())
	    markDead();
	if (isDead() || teleport_)
	    return;
	KSprite::advance(phase);
	QList<QGraphicsItem*> hits = ship_->collidingItems();
	QList<QGraphicsItem*>::Iterator i;
	for (i=hits.begin(); i!=hits.end(); ++i) {
	    if ((*i)->type() <= ID_Base)
		continue;
	    KSprite* sprite = (KSprite*)(*i);
	    if (sprite->isRock()) {
		if (shield_->isUp()) {
		    /*
		      The ship hit a rock with the shield up.
		      The rock is marked for death, which will
		      cause it to break up or just disappear in
		      in phase 1.

		      The shield's strength is reduced by an
		      amount commensurate with the rock size.
		      If the strength goes to 0, the shield
		      will be dropped in phase 1.
		     */
		    sprite->markDead();
		    int s = 1;
		    if (sprite->isLargeRock())
			s = 3;
		    else if (sprite->isMediumRock())
			s = 2;
		    int pl = s * (SHIELD_HIT_COST - (shield_->strength()*2));
		    shield_->reduceStrength(s);
		    reducePowerLevel(pl);
		}
		else {
		    /*
		      The ship hit a rock with the shield down.
		      Mark the ship dead and return. The ship
		      will be exploded in phase 1.
		     */
                    view_->setCanPause(false);
		    markDead();
		    shield_->markDead();
		    return;
		}
	    }
	    else if (sprite->isPowerup()) {
		if (shield_->isUp()) {
		    sprite->markDead();
		}
		else {
		    /*
		      The ship hit a powerup with the shield down.
		      Mark the powerup for apply. It will be applied
		      to the ship in phase 1, if the ship survives.
		      Also mark the powerup dead, ie consumed.
		     */
		    sprite->markApply();
		    sprite->markDead();
		    return;
		}
	    }
            else if (powerLevel() <= EMPTY_SHIP_POWER_LEVEL) {
                ship_->markDead();
                shield_->markDead();
            }
	}
    }
    else { // phase 1
	if (isDead() || dying()) {
	    explode(); // shatters the ship into spinning fragments.
	    delete this;
	    return;
	}
	if (rotateSlow_)
	    rotateSlow_--;

	if (rotateLeft_) {
	    angleIndex_ -= rotateSlow_ ? 1 : rotationRate_;
	    if (angleIndex_ < 0)
		angleIndex_ = SHIP_STEPS-1;
	    angle_ = angleIndex_ * PI_X_2 / SHIP_STEPS;
	    cosangle_ = cos(angle_);
	    sinangle_ = sin(angle_);
	}

	if (rotateRight_) {
	    angleIndex_ += rotateSlow_ ? 1 : rotationRate_;
	    if (angleIndex_ >= SHIP_STEPS)
		angleIndex_ = 0;
	    angle_ = angleIndex_ * PI_X_2 / SHIP_STEPS;
	    cosangle_ = cos(angle_);
	    sinangle_ = sin(angle_);
	}

	if (isBraking()) {
	    stopEngine();
	    stopRotation();
	    if ((fabs(dx_) < 2.5) && (fabs(dy_) < 2.5)) {
		dx_ = 0.0;
		dy_ = 0.0;
		setVelocity(dx_,dy_);
		releaseBrakes();
	    }
	    else {
		double motionAngle = atan2(-dy_,-dx_);
		if (angle_ > M_PI)
		    angle_ -= PI_X_2;
		double angleDiff = angle_ - motionAngle;
		if (angleDiff > M_PI)
		    angleDiff = PI_X_2 - angleDiff;
		else if (angleDiff < -M_PI)
		    angleDiff = PI_X_2 + angleDiff;
		double fdiff = fabs(angleDiff);
		if (fdiff > 0.08) {
		    if (angleDiff > 0)
			rotateLeft_ = true;
		    else if (angleDiff < 0)
			rotateRight_ = true;
		    if (fdiff > 0.6)
			rotationRate_ = brakeForce() + 1;
		    else if (fdiff > 0.4)
			rotationRate_ = 2;
		    else
			rotationRate_ = 1;

		    if (rotationRate_ > 5)
			rotationRate_ = 5;
		}
		else if ((fabs(dx_)>1) || (fabs(dy_)>1)) {
		    startEngine();
		    // we'll make braking a bit faster
		    dx_ += cosangle_/6 * (brakeForce() - 1);
		    dy_ += sinangle_/6 * (brakeForce() - 1);
		    reducePowerLevel(BRAKE_ON_COST);
		    KExhaust::add(ship_->x() + 10 - cosangle_*11,
				  ship_->y() + 10 - sinangle_*11,
				  dx_-cosangle_,
				  dy_-sinangle_,
				  brakeForce()+1);
		}
	    }
	}
	else if (engineIsOn()) {
	    /*
	      The ship has a terminal velocity, but trying
	      to go faster still uses fuel (can go faster
	      diagonally - don't care).
	    */
	    double thrustx = cosangle_/8;
	    double thrusty = sinangle_/8;
	    if (fabs(dx_ + thrustx) < MAX_SHIP_SPEED)
		dx_ += thrustx;
	    if (fabs(dy_ + thrusty) < MAX_SHIP_SPEED)
		dy_ += thrusty;
	    setVelocity(dx_,dy_);
	    reducePowerLevel(5);
	    KExhaust::add(x() + 10 - cosangle_*10,
			  y() + 10 - sinangle_*10,
			  dx_-cosangle_,
			  dy_-sinangle_,
			  3);
	}

	setImage(angleIndex_ >> 1);

	if (teleport_) {
	    int ra = rand() % 10;
	    if(ra == 0)
		ra += rand() % 20;
	    int xra = ra * 60 + ((rand() % 20) * (rand() % 20));
	    int yra = ra * 50 - ((rand() % 20) * (rand() % 20));
	    setPos(xra,yra);
	    teleport_ = false;
	    if (teleportCount_ > 0) {
		--teleportCount_;
		view_->markVitalsChanged();
	    }
	    wrap();
	}

	if (shield_->isUp()) {
	    /*
	      The shield's position always depends on the
	      ship's position.
	     */
	    static int sf = 0;
	    sf++;
	    if (sf % 2)
		shield_->advanceImage();
	    shield_->setPos(x()-5,y()-5);
	    shield_->show();
	}

	if (isShooting()) {
	    int maxMissiles = firePower_ + 2;
	    if (canShoot() && (KMissile::missiles() < maxMissiles)) {
		KMissile* missile = new KMissile();
		missile->setMaximumAge(12);
		missile->setPos(11 + x() + cosangle_ * 11,
				11 + y() + sinangle_ * 11);
		missile->setVelocity(dx_ + cosangle_ * MISSILE_SPEED,
				     dy_ + sinangle_ * MISSILE_SPEED);
		missile->show();
		reducePowerLevel(1);
		view_->reportMissileFired();
		int delay = 5 - firePower_;
		if (delay < 0)
		    delay = 0;
		delayShooting(delay); // delay firing next missile.
	    }
	    decrementNextShotDelay();
	}
    }
}
Exemple #25
0
Renderer::~Renderer() {
	stopEngine();
}