// must implement inherited abstract methods public void surfaceCreated(SurfaceHolder holder) { // Create the thread if (!myThread.isAlive()) { myThread = new GameThread(getHolder(), this); myThread.startRun(true); myThread.start(); } }
@Override public void surfaceCreated(SurfaceHolder holder) { // 启动主线程执行部分 paint.setTextSize(15); if (thread != null) { thread.needStop = true; } thread = new GameThread(surfaceHolder); thread.start(); }
public void killThread() { boolean retry = true; gthread.setRunning(false); while (retry) { try { gthread.join(); retry = false; } catch (InterruptedException e) { } } }
/* * Callback invoked when the Surface has been destroyed. */ public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { Log.e("Tile Game Example", e.getMessage()); } } }
public void surfaceDestroyed(SurfaceHolder holder) { if (thread != null) { boolean retry = true; thread.setRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { } } } thread = null; }
public void surfaceDestroyed(SurfaceHolder holder) { // Destroy the thread if (myThread.isAlive()) { myThread.startRun(false); } boolean retry = true; while (retry) { try { myThread.join(); retry = false; } catch (InterruptedException e) { } } }
/** * This constructor initializes the engine by initializing its systems, subsystems and managers. * It also verifies that some required systems are up and running after they have been * initialized. * * @param subsystems Typical subsystems lists contain graphics, timer, audio and input subsystems. */ public TerasologyEngine(Collection<EngineSubsystem> subsystems) { Stopwatch totalInitTime = Stopwatch.createStarted(); this.subsystems = Queues.newArrayDeque(subsystems); try { logger.info("Initializing Terasology..."); logEnvironmentInfo(); SplashScreen.getInstance().post("Loading config file ..."); initConfig(); SplashScreen.getInstance().post("Pre-initialize subsystems ..."); preInitSubsystems(); // time must be set here as it is required by some of the managers. verifyRequiredSystemIsRegistered(Time.class); time = (EngineTime) CoreRegistry.get(Time.class); GameThread.setToCurrentThread(); initManagers(); SplashScreen.getInstance().post("Post-initialize subsystems ..."); postInitSubsystems(); verifyRequiredSystemIsRegistered(DisplayDevice.class); verifyRequiredSystemIsRegistered(RenderingSubsystemFactory.class); verifyRequiredSystemIsRegistered(InputSystem.class); SplashScreen.getInstance().post("Initialize assets ..."); initAssets(); // TODO: Review - The advanced monitor shouldn't be hooked-in this way (see issue #692) initAdvancedMonitor(); engineState = EngineState.INITIALIZED; } catch (RuntimeException e) { logger.error("Failed to initialise Terasology", e); cleanup(); throw e; } double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS); logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds)); }
/** 开始游戏 */ private void startGame() { initEntity(); GameConfig.isGameStart = true; GameConfig.isPutWhiteBall = false; GameConfig.isReady = false; if (GameConfig.isGameStart && !GameConfig.isPutWhiteBall) { setCursor(ImageRes.hand_cursor); } mGameThread = new GameThread(); mGameThread.start(); mGamePaintThread = new GamePaintThread(); mGamePaintThread.start(); }
@Override protected void doDraw(Canvas canvas) { if (canvas == null) return; super.doDraw(canvas); for (Apple apple : apples) { apple.draw(canvas); } canvas.drawBitmap( mPaddle, mPaddleX - mPaddle.getWidth() / 2, mCanvasHeight - mPaddle.getHeight() / 2, null); }
public void surfaceCreated(SurfaceHolder holder) { if (thread == null && !shutdown) { thread = new GameThread( this, game, holder, new Handler() { @Override public void handleMessage(Message m) {} }); thread.start(); } }
/** * The main loop runs until the EngineState is set back to INITIALIZED by shutdown() or until the * OS requests the application's window to be closed. Engine cleanup and disposal occur * afterwards. */ private void mainLoop() { PerformanceMonitor.startActivity("Other"); // MAIN GAME LOOP while (!shutdownRequested) { assetTypeManager.reloadChangedOnDisk(); processPendingState(); if (currentState == null) { shutdown(); break; } Iterator<Float> updateCycles = timeSubsystem.getEngineTime().tick(); for (EngineSubsystem subsystem : allSubsystems) { try (Activity ignored = PerformanceMonitor.startActivity(subsystem.getName() + " PreUpdate")) { subsystem.preUpdate(currentState, timeSubsystem.getEngineTime().getRealDelta()); } } while (updateCycles.hasNext()) { float updateDelta = updateCycles.next(); // gameTime gets updated here! try (Activity ignored = PerformanceMonitor.startActivity("Main Update")) { currentState.update(updateDelta); } } // Waiting processes are set by modules via GameThread.a/synch() methods. GameThread.processWaitingProcesses(); for (EngineSubsystem subsystem : getSubsystems()) { try (Activity ignored = PerformanceMonitor.startActivity(subsystem.getName() + " Subsystem postUpdate")) { subsystem.postUpdate(currentState, timeSubsystem.getEngineTime().getRealDelta()); } } assetTypeManager.disposedUnusedAssets(); PerformanceMonitor.rollCycle(); PerformanceMonitor.startActivity("Other"); } PerformanceMonitor.endActivity(); }
private void initialize() { Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Stopwatch totalInitTime = Stopwatch.createStarted(); try { logger.info("Initializing Terasology..."); logEnvironmentInfo(); // TODO: Need to get everything thread safe and get rid of the concept of "GameThread" as much // as possible. GameThread.setToCurrentThread(); preInitSubsystems(); initManagers(); initSubsystems(); changeStatus(TerasologyEngineStatus.INITIALIZING_ASSET_MANAGEMENT); initAssets(); EnvironmentSwitchHandler environmentSwitcher = new EnvironmentSwitchHandler(); rootContext.put(EnvironmentSwitchHandler.class, environmentSwitcher); environmentSwitcher.handleSwitchToGameEnvironment(rootContext); postInitSubsystems(); verifyInitialisation(); /** * Prevent objects being put in engine context after init phase. Engine states should * use/create a child context. */ CoreRegistry.setContext(null); } catch (RuntimeException e) { logger.error("Failed to initialise Terasology", e); cleanup(); throw e; } double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS); logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds)); }
/** * The game view. * * @param Context context * @param Activity activity * @param int stage - The stage to load. * @param int level - The level to load. * @param float screenDensity - The screen density. */ public GameView(Context context, Play activity, int stage, int level, float screenDensity) { super(context); mGameContext = context; mGameActivity = activity; mScreenDensity = screenDensity; mPlayerStage = stage; mPlayerLevel = level; mGameTileData = new GameTileData(context); mGameLevelTileData = new GameLevelTileData(context); mGameTileTemplates = mGameTileData.getTilesData(); SurfaceHolder holder = getHolder(); holder.addCallback(this); // create thread only; it's started in surfaceCreated() thread = new GameThread(holder, context, null); setFocusable(true); mUiTextPaint = new Paint(); mUiTextPaint.setStyle(Paint.Style.FILL); mUiTextPaint.setColor(Color.YELLOW); mUiTextPaint.setAntiAlias(true); Typeface uiTypeface = Typeface.createFromAsset(activity.getAssets(), "fonts/Molot.otf"); if (uiTypeface != null) { mUiTextPaint.setTypeface(uiTypeface); } mUiTextPaint.setTextSize( mGameContext .getApplicationContext() .getResources() .getDimensionPixelSize(R.dimen.ui_text_size)); startLevel(); thread.doStart(); }
/* * Callback invoked when the Surface has been created and is ready to be * used. */ public void surfaceCreated(SurfaceHolder holder) { // start the thread here so that we don't busy-wait in run() // waiting for the surface to be created if (thread.getState() == Thread.State.TERMINATED) { thread = new GameThread(holder, getContext(), new Handler()); thread.setRunning(true); thread.start(); thread.doStart(); startLevel(); } else { thread.setRunning(true); thread.start(); } }
/** Callback invoked when the surface dimensions change. */ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { thread.setSurfaceSize(width, height); }
/* * Implemented in GameView.java, needs an import of android.view.MotionEvent * * calls getGameState().motionDetected() if there’s a touch on the screen. */ public boolean onTouchEvent(MotionEvent event) { return thread.getGameState().motionDetected(event); }
/* * Callback invoked when the Surface has been destroyed and must no longer * be touched. WARNING: after this method returns, the Surface/Canvas must * never be touched again! */ public void surfaceDestroyed(SurfaceHolder holder) { thread.end(); }
/* * Callback invoked when the Surface has been created and is ready to be * used. */ public void surfaceCreated(SurfaceHolder holder) { thread.begin(); thread.start(); }
public void onPause() { super.onPause(); gameThread.setRunning(false); }
/** * The main loop runs until the EngineState is set back to INITIALIZED by shutdown() or until the * OS requests the application's window to be closed. Engine cleanup and disposal occur * afterwards. */ private void mainLoop() { NetworkSystem networkSystem = CoreRegistry.get(NetworkSystem.class); DisplayDevice display = CoreRegistry.get(DisplayDevice.class); PerformanceMonitor.startActivity("Other"); // MAIN GAME LOOP while (engineState == EngineState.RUNNING && !display.isCloseRequested()) { long totalDelta; float updateDelta; float subsystemsDelta; // Only process rendering and updating once a second if (!display.isActive() && isHibernationAllowed()) { time.setPaused(true); Iterator<Float> updateCycles = time.tick(); while (updateCycles.hasNext()) { updateCycles.next(); } try { Thread.sleep(100); } catch (InterruptedException e) { logger.warn("Display inactivity sleep interrupted", e); } display.processMessages(); time.setPaused(false); continue; } processPendingState(); if (currentState == null) { shutdown(); break; } Iterator<Float> updateCycles = time.tick(); try (Activity ignored = PerformanceMonitor.startActivity("Network Update")) { networkSystem.update(); } totalDelta = 0; while (updateCycles.hasNext()) { updateDelta = updateCycles.next(); // gameTime gets updated here! totalDelta += time.getDeltaInMs(); try (Activity ignored = PerformanceMonitor.startActivity("Main Update")) { currentState.update(updateDelta); } } subsystemsDelta = totalDelta / 1000f; for (EngineSubsystem subsystem : getSubsystems()) { try (Activity ignored = PerformanceMonitor.startActivity(subsystem.getClass().getSimpleName())) { subsystem.preUpdate(currentState, subsystemsDelta); } } // Waiting processes are set by modules via GameThread.a/synch() methods. GameThread.processWaitingProcesses(); for (EngineSubsystem subsystem : getSubsystems()) { try (Activity ignored = PerformanceMonitor.startActivity(subsystem.getClass().getSimpleName())) { subsystem.postUpdate(currentState, subsystemsDelta); } } PerformanceMonitor.rollCycle(); PerformanceMonitor.startActivity("Other"); } PerformanceMonitor.endActivity(); // This becomes important only if display.isCloseRequested() is true. // In all other circumstances the EngineState is already set to // INITIALIZED by the time the flow gets here. engineState = EngineState.INITIALIZED; }
// Implemented as part of the SurfaceHolder.Callback interface @Override public void surfaceCreated(SurfaceHolder holder) { thread.start(); }
// Implemented as part of the SurfaceHolder.Callback interface @Override public void surfaceDestroyed(SurfaceHolder holder) { thread.stopGame(); }
@Override public void onWindowFocusChanged(boolean hasWindowFocus) { if (!hasWindowFocus) thread.pause(); }
@Override public void onWindowFocusChanged(boolean hasWindowFocus) { if (thread != null) { thread.onWindowFocusChanged(hasWindowFocus); } }
@Override public boolean onKeyUp(int keyCode, KeyEvent msg) { if (thread != null) return thread.doKeyUp(keyCode, msg); return false; }
/** Loads and starts the current level. */ private void startLevel() { parseGameLevelData(); setPlayerStart(); thread.unpause(); }
public void setThread(GameThread gameThread) { this.thread = gameThread; thread.setMSurfaceHolder(getHolder()); }