clang-format the world.

This used to be done by CI but we ripped that out since there wasn't any
good way to ensure that CI and and local workflows were using the same
clang-format. Back when it was in CI, the pointer alignment was
configured incorrectly (we used the Google style presets, but those are
alignment preserving rather than actually style enforcing). Reformat
everything since the .clang-format file has changed since then so I stop
including so many unrelated edits in my commits.
This commit is contained in:
Dan Albert
2025-08-26 15:47:21 -07:00
committed by Dan Albert
parent 25757933bb
commit 5c283e26bc
63 changed files with 564 additions and 563 deletions

View File

@@ -50,12 +50,12 @@ class AudioDelay : public AudioFormat {
size_t getDelayTime(void) const; size_t getDelayTime(void) const;
void setDecayWeight(float weight); void setDecayWeight(float weight);
float getDecayWeight(void) const; float getDecayWeight(void) const;
void process(int16_t *liveAudio, int32_t numFrames); void process(int16_t* liveAudio, int32_t numFrames);
private: private:
size_t delayTime_ = 0; size_t delayTime_ = 0;
float decayWeight_ = 0.5; float decayWeight_ = 0.5;
void *buffer_ = nullptr; void* buffer_ = nullptr;
size_t bufCapacity_ = 0; size_t bufCapacity_ = 0;
size_t bufSize_ = 0; size_t bufSize_ = 0;
size_t curPos_ = 0; size_t curPos_ = 0;

View File

@@ -35,24 +35,24 @@ struct EchoAudioEngine {
SLObjectItf slEngineObj_; SLObjectItf slEngineObj_;
SLEngineItf slEngineItf_; SLEngineItf slEngineItf_;
AudioRecorder *recorder_; AudioRecorder* recorder_;
AudioPlayer *player_; AudioPlayer* player_;
AudioQueue *freeBufQueue_; // Owner of the queue AudioQueue* freeBufQueue_; // Owner of the queue
AudioQueue *recBufQueue_; // Owner of the queue AudioQueue* recBufQueue_; // Owner of the queue
sample_buf *bufs_; sample_buf* bufs_;
uint32_t bufCount_; uint32_t bufCount_;
uint32_t frameCount_; uint32_t frameCount_;
int64_t echoDelay_; int64_t echoDelay_;
float echoDecay_; float echoDecay_;
AudioDelay *delayEffect_; AudioDelay* delayEffect_;
}; };
static EchoAudioEngine engine; static EchoAudioEngine engine;
bool EngineService(void *ctx, uint32_t msg, void *data); bool EngineService(void* ctx, uint32_t msg, void* data);
JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_createSLEngine( JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_createSLEngine(
JNIEnv *env, jclass type, jint sampleRate, jint framesPerBuf, JNIEnv* env, jclass type, jint sampleRate, jint framesPerBuf,
jlong delayInMs, jfloat decay) { jlong delayInMs, jfloat decay) {
SLresult result; SLresult result;
memset(&engine, 0, sizeof(engine)); memset(&engine, 0, sizeof(engine));
@@ -103,7 +103,7 @@ JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_createSLEngine(
} }
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
Java_com_google_sample_echo_MainActivity_configureEcho(JNIEnv *env, jclass type, Java_com_google_sample_echo_MainActivity_configureEcho(JNIEnv* env, jclass type,
jint delayInMs, jint delayInMs,
jfloat decay) { jfloat decay) {
engine.echoDelay_ = delayInMs; engine.echoDelay_ = delayInMs;
@@ -116,7 +116,7 @@ Java_com_google_sample_echo_MainActivity_configureEcho(JNIEnv *env, jclass type,
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
Java_com_google_sample_echo_MainActivity_createSLBufferQueueAudioPlayer( Java_com_google_sample_echo_MainActivity_createSLBufferQueueAudioPlayer(
JNIEnv *env, jclass type) { JNIEnv* env, jclass type) {
SampleFormat sampleFormat; SampleFormat sampleFormat;
memset(&sampleFormat, 0, sizeof(sampleFormat)); memset(&sampleFormat, 0, sizeof(sampleFormat));
sampleFormat.pcmFormat_ = (uint16_t)engine.bitsPerSample_; sampleFormat.pcmFormat_ = (uint16_t)engine.bitsPerSample_;
@@ -131,14 +131,14 @@ Java_com_google_sample_echo_MainActivity_createSLBufferQueueAudioPlayer(
if (engine.player_ == nullptr) return JNI_FALSE; if (engine.player_ == nullptr) return JNI_FALSE;
engine.player_->SetBufQueue(engine.recBufQueue_, engine.freeBufQueue_); engine.player_->SetBufQueue(engine.recBufQueue_, engine.freeBufQueue_);
engine.player_->RegisterCallback(EngineService, (void *)&engine); engine.player_->RegisterCallback(EngineService, (void*)&engine);
return JNI_TRUE; return JNI_TRUE;
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_deleteSLBufferQueueAudioPlayer( Java_com_google_sample_echo_MainActivity_deleteSLBufferQueueAudioPlayer(
JNIEnv *env, jclass type) { JNIEnv* env, jclass type) {
if (engine.player_) { if (engine.player_) {
delete engine.player_; delete engine.player_;
engine.player_ = nullptr; engine.player_ = nullptr;
@@ -146,7 +146,7 @@ Java_com_google_sample_echo_MainActivity_deleteSLBufferQueueAudioPlayer(
} }
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
Java_com_google_sample_echo_MainActivity_createAudioRecorder(JNIEnv *env, Java_com_google_sample_echo_MainActivity_createAudioRecorder(JNIEnv* env,
jclass type) { jclass type) {
SampleFormat sampleFormat; SampleFormat sampleFormat;
memset(&sampleFormat, 0, sizeof(sampleFormat)); memset(&sampleFormat, 0, sizeof(sampleFormat));
@@ -161,12 +161,12 @@ Java_com_google_sample_echo_MainActivity_createAudioRecorder(JNIEnv *env,
return JNI_FALSE; return JNI_FALSE;
} }
engine.recorder_->SetBufQueues(engine.freeBufQueue_, engine.recBufQueue_); engine.recorder_->SetBufQueues(engine.freeBufQueue_, engine.recBufQueue_);
engine.recorder_->RegisterCallback(EngineService, (void *)&engine); engine.recorder_->RegisterCallback(EngineService, (void*)&engine);
return JNI_TRUE; return JNI_TRUE;
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_deleteAudioRecorder(JNIEnv *env, Java_com_google_sample_echo_MainActivity_deleteAudioRecorder(JNIEnv* env,
jclass type) { jclass type) {
if (engine.recorder_) delete engine.recorder_; if (engine.recorder_) delete engine.recorder_;
@@ -174,7 +174,7 @@ Java_com_google_sample_echo_MainActivity_deleteAudioRecorder(JNIEnv *env,
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_startPlay(JNIEnv *env, jclass type) { Java_com_google_sample_echo_MainActivity_startPlay(JNIEnv* env, jclass type) {
engine.frameCount_ = 0; engine.frameCount_ = 0;
/* /*
* start player: make it into waitForData state * start player: make it into waitForData state
@@ -187,7 +187,7 @@ Java_com_google_sample_echo_MainActivity_startPlay(JNIEnv *env, jclass type) {
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_stopPlay(JNIEnv *env, jclass type) { Java_com_google_sample_echo_MainActivity_stopPlay(JNIEnv* env, jclass type) {
engine.recorder_->Stop(); engine.recorder_->Stop();
engine.player_->Stop(); engine.player_->Stop();
@@ -198,7 +198,7 @@ Java_com_google_sample_echo_MainActivity_stopPlay(JNIEnv *env, jclass type) {
} }
JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_deleteSLEngine( JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_deleteSLEngine(
JNIEnv *env, jclass type) { JNIEnv* env, jclass type) {
delete engine.recBufQueue_; delete engine.recBufQueue_;
delete engine.freeBufQueue_; delete engine.freeBufQueue_;
releaseSampleBufs(engine.bufs_, engine.bufCount_); releaseSampleBufs(engine.bufs_, engine.bufCount_);
@@ -236,19 +236,19 @@ uint32_t dbgEngineGetBufCount(void) {
/* /*
* simple message passing for player/recorder to communicate with engine * simple message passing for player/recorder to communicate with engine
*/ */
bool EngineService(void *ctx, uint32_t msg, void *data) { bool EngineService(void* ctx, uint32_t msg, void* data) {
assert(ctx == &engine); assert(ctx == &engine);
switch (msg) { switch (msg) {
case ENGINE_SERVICE_MSG_RETRIEVE_DUMP_BUFS: { case ENGINE_SERVICE_MSG_RETRIEVE_DUMP_BUFS: {
*(static_cast<uint32_t *>(data)) = dbgEngineGetBufCount(); *(static_cast<uint32_t*>(data)) = dbgEngineGetBufCount();
break; break;
} }
case ENGINE_SERVICE_MSG_RECORDED_AUDIO_AVAILABLE: { case ENGINE_SERVICE_MSG_RECORDED_AUDIO_AVAILABLE: {
// adding audio delay effect // adding audio delay effect
sample_buf *buf = static_cast<sample_buf *>(data); sample_buf* buf = static_cast<sample_buf*>(data);
assert(engine.fastPathFramesPerBuf_ == assert(engine.fastPathFramesPerBuf_ ==
buf->size_ / engine.sampleChannels_ / (engine.bitsPerSample_ / 8)); buf->size_ / engine.sampleChannels_ / (engine.bitsPerSample_ / 8));
engine.delayEffect_->process(reinterpret_cast<int16_t *>(buf->buf_), engine.delayEffect_->process(reinterpret_cast<int16_t*>(buf->buf_),
engine.fastPathFramesPerBuf_); engine.fastPathFramesPerBuf_);
break; break;
} }

View File

@@ -28,8 +28,8 @@
* very regular, you could buffer much less audio samples between * very regular, you could buffer much less audio samples between
* recorder and player, hence lower latency. * recorder and player, hence lower latency.
*/ */
void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *ctx) { void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* ctx) {
(static_cast<AudioPlayer *>(ctx))->ProcessSLCallback(bq); (static_cast<AudioPlayer*>(ctx))->ProcessSLCallback(bq);
} }
void AudioPlayer::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) { void AudioPlayer::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
#ifdef ENABLE_LOG #ifdef ENABLE_LOG
@@ -39,7 +39,7 @@ void AudioPlayer::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
// retrieve the finished device buf and put onto the free queue // retrieve the finished device buf and put onto the free queue
// so recorder could re-use it // so recorder could re-use it
sample_buf *buf; sample_buf* buf;
if (!devShadowQueue_->front(&buf)) { if (!devShadowQueue_->front(&buf)) {
/* /*
* This should not happen: we got a callback, * This should not happen: we got a callback,
@@ -87,7 +87,7 @@ void AudioPlayer::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
} }
} }
AudioPlayer::AudioPlayer(SampleFormat *sampleFormat, SLEngineItf slEngine) AudioPlayer::AudioPlayer(SampleFormat* sampleFormat, SLEngineItf slEngine)
: freeQueue_(nullptr), : freeQueue_(nullptr),
playQueue_(nullptr), playQueue_(nullptr),
devShadowQueue_(nullptr), devShadowQueue_(nullptr),
@@ -176,7 +176,7 @@ AudioPlayer::~AudioPlayer() {
(*playerObjectItf_)->Destroy(playerObjectItf_); (*playerObjectItf_)->Destroy(playerObjectItf_);
} }
// Consume all non-completed audio buffers // Consume all non-completed audio buffers
sample_buf *buf = NULL; sample_buf* buf = NULL;
while (devShadowQueue_->front(&buf)) { while (devShadowQueue_->front(&buf)) {
buf->size_ = 0; buf->size_ = 0;
devShadowQueue_->pop(); devShadowQueue_->pop();
@@ -200,7 +200,7 @@ AudioPlayer::~AudioPlayer() {
delete[] silentBuf_.buf_; delete[] silentBuf_.buf_;
} }
void AudioPlayer::SetBufQueue(AudioQueue *playQ, AudioQueue *freeQ) { void AudioPlayer::SetBufQueue(AudioQueue* playQ, AudioQueue* freeQ) {
playQueue_ = playQ; playQueue_ = playQ;
freeQueue_ = freeQ; freeQueue_ = freeQ;
} }
@@ -251,7 +251,7 @@ void AudioPlayer::Stop(void) {
#endif #endif
} }
void AudioPlayer::RegisterCallback(ENGINE_CALLBACK cb, void *ctx) { void AudioPlayer::RegisterCallback(ENGINE_CALLBACK cb, void* ctx) {
callback_ = cb; callback_ = cb;
ctx_ = ctx; ctx_ = ctx;
} }

View File

@@ -30,27 +30,27 @@ class AudioPlayer {
SLAndroidSimpleBufferQueueItf playBufferQueueItf_; SLAndroidSimpleBufferQueueItf playBufferQueueItf_;
SampleFormat sampleInfo_; SampleFormat sampleInfo_;
AudioQueue *freeQueue_; // user AudioQueue* freeQueue_; // user
AudioQueue *playQueue_; // user AudioQueue* playQueue_; // user
AudioQueue *devShadowQueue_; // owner AudioQueue* devShadowQueue_; // owner
ENGINE_CALLBACK callback_; ENGINE_CALLBACK callback_;
void *ctx_; void* ctx_;
sample_buf silentBuf_; sample_buf silentBuf_;
#ifdef ENABLE_LOG #ifdef ENABLE_LOG
AndroidLog *logFile_; AndroidLog* logFile_;
#endif #endif
std::mutex stopMutex_; std::mutex stopMutex_;
public: public:
explicit AudioPlayer(SampleFormat *sampleFormat, SLEngineItf engine); explicit AudioPlayer(SampleFormat* sampleFormat, SLEngineItf engine);
~AudioPlayer(); ~AudioPlayer();
void SetBufQueue(AudioQueue *playQ, AudioQueue *freeQ); void SetBufQueue(AudioQueue* playQ, AudioQueue* freeQ);
SLresult Start(void); SLresult Start(void);
void Stop(void); void Stop(void);
void ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq); void ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq);
uint32_t dbgGetDevBufCount(void); uint32_t dbgGetDevBufCount(void);
void RegisterCallback(ENGINE_CALLBACK cb, void *ctx); void RegisterCallback(ENGINE_CALLBACK cb, void* ctx);
}; };
#endif // NATIVE_AUDIO_AUDIO_PLAYER_H #endif // NATIVE_AUDIO_AUDIO_PLAYER_H

View File

@@ -22,8 +22,8 @@
* bqRecorderCallback(): called for every buffer is full; * bqRecorderCallback(): called for every buffer is full;
* pass directly to handler * pass directly to handler
*/ */
void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *rec) { void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void* rec) {
(static_cast<AudioRecorder *>(rec))->ProcessSLCallback(bq); (static_cast<AudioRecorder*>(rec))->ProcessSLCallback(bq);
} }
void AudioRecorder::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) { void AudioRecorder::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
@@ -31,7 +31,7 @@ void AudioRecorder::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
recLog_->logTime(); recLog_->logTime();
#endif #endif
assert(bq == recBufQueueItf_); assert(bq == recBufQueueItf_);
sample_buf *dataBuf = NULL; sample_buf* dataBuf = NULL;
devShadowQueue_->front(&dataBuf); devShadowQueue_->front(&dataBuf);
devShadowQueue_->pop(); devShadowQueue_->pop();
dataBuf->size_ = dataBuf->cap_; // device only calls us when it is really dataBuf->size_ = dataBuf->cap_; // device only calls us when it is really
@@ -40,7 +40,7 @@ void AudioRecorder::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
callback_(ctx_, ENGINE_SERVICE_MSG_RECORDED_AUDIO_AVAILABLE, dataBuf); callback_(ctx_, ENGINE_SERVICE_MSG_RECORDED_AUDIO_AVAILABLE, dataBuf);
recQueue_->push(dataBuf); recQueue_->push(dataBuf);
sample_buf *freeBuf; sample_buf* freeBuf;
while (freeQueue_->front(&freeBuf) && devShadowQueue_->push(freeBuf)) { while (freeQueue_->front(&freeBuf) && devShadowQueue_->push(freeBuf)) {
freeQueue_->pop(); freeQueue_->pop();
SLresult result = (*bq)->Enqueue(bq, freeBuf->buf_, freeBuf->cap_); SLresult result = (*bq)->Enqueue(bq, freeBuf->buf_, freeBuf->cap_);
@@ -55,7 +55,7 @@ void AudioRecorder::ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq) {
} }
} }
AudioRecorder::AudioRecorder(SampleFormat *sampleFormat, SLEngineItf slEngine) AudioRecorder::AudioRecorder(SampleFormat* sampleFormat, SLEngineItf slEngine)
: freeQueue_(nullptr), : freeQueue_(nullptr),
recQueue_(nullptr), recQueue_(nullptr),
devShadowQueue_(nullptr), devShadowQueue_(nullptr),
@@ -138,7 +138,7 @@ SLboolean AudioRecorder::Start(void) {
SLASSERT(result); SLASSERT(result);
for (int i = 0; i < RECORD_DEVICE_KICKSTART_BUF_COUNT; i++) { for (int i = 0; i < RECORD_DEVICE_KICKSTART_BUF_COUNT; i++) {
sample_buf *buf = NULL; sample_buf* buf = NULL;
if (!freeQueue_->front(&buf)) { if (!freeQueue_->front(&buf)) {
LOGE("=====OutOfFreeBuffers @ startingRecording @ (%d)", i); LOGE("=====OutOfFreeBuffers @ startingRecording @ (%d)", i);
break; break;
@@ -185,7 +185,7 @@ AudioRecorder::~AudioRecorder() {
} }
if (devShadowQueue_) { if (devShadowQueue_) {
sample_buf *buf = NULL; sample_buf* buf = NULL;
while (devShadowQueue_->front(&buf)) { while (devShadowQueue_->front(&buf)) {
devShadowQueue_->pop(); devShadowQueue_->pop();
freeQueue_->push(buf); freeQueue_->push(buf);
@@ -199,13 +199,13 @@ AudioRecorder::~AudioRecorder() {
#endif #endif
} }
void AudioRecorder::SetBufQueues(AudioQueue *freeQ, AudioQueue *recQ) { void AudioRecorder::SetBufQueues(AudioQueue* freeQ, AudioQueue* recQ) {
assert(freeQ && recQ); assert(freeQ && recQ);
freeQueue_ = freeQ; freeQueue_ = freeQ;
recQueue_ = recQ; recQueue_ = recQ;
} }
void AudioRecorder::RegisterCallback(ENGINE_CALLBACK cb, void *ctx) { void AudioRecorder::RegisterCallback(ENGINE_CALLBACK cb, void* ctx) {
callback_ = cb; callback_ = cb;
ctx_ = ctx; ctx_ = ctx;
} }

View File

@@ -30,26 +30,26 @@ class AudioRecorder {
SLAndroidSimpleBufferQueueItf recBufQueueItf_; SLAndroidSimpleBufferQueueItf recBufQueueItf_;
SampleFormat sampleInfo_; SampleFormat sampleInfo_;
AudioQueue *freeQueue_; // user AudioQueue* freeQueue_; // user
AudioQueue *recQueue_; // user AudioQueue* recQueue_; // user
AudioQueue *devShadowQueue_; // owner AudioQueue* devShadowQueue_; // owner
uint32_t audioBufCount; uint32_t audioBufCount;
ENGINE_CALLBACK callback_; ENGINE_CALLBACK callback_;
void *ctx_; void* ctx_;
public: public:
explicit AudioRecorder(SampleFormat *, SLEngineItf engineEngine); explicit AudioRecorder(SampleFormat*, SLEngineItf engineEngine);
~AudioRecorder(); ~AudioRecorder();
SLboolean Start(void); SLboolean Start(void);
SLboolean Stop(void); SLboolean Stop(void);
void SetBufQueues(AudioQueue *freeQ, AudioQueue *recQ); void SetBufQueues(AudioQueue* freeQ, AudioQueue* recQ);
void ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq); void ProcessSLCallback(SLAndroidSimpleBufferQueueItf bq);
void RegisterCallback(ENGINE_CALLBACK cb, void *ctx); void RegisterCallback(ENGINE_CALLBACK cb, void* ctx);
int32_t dbgGetDevBufCount(void); int32_t dbgGetDevBufCount(void);
#ifdef ENABLE_LOG #ifdef ENABLE_LOG
AndroidLog *recLog_; AndroidLog* recLog_;
#endif #endif
}; };

View File

@@ -23,28 +23,28 @@ extern "C" {
#endif #endif
JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_createSLEngine( JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_createSLEngine(
JNIEnv *env, jclass, jint, jint, jlong delayInMs, jfloat decay); JNIEnv* env, jclass, jint, jint, jlong delayInMs, jfloat decay);
JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_deleteSLEngine( JNIEXPORT void JNICALL Java_com_google_sample_echo_MainActivity_deleteSLEngine(
JNIEnv *env, jclass type); JNIEnv* env, jclass type);
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
Java_com_google_sample_echo_MainActivity_createSLBufferQueueAudioPlayer( Java_com_google_sample_echo_MainActivity_createSLBufferQueueAudioPlayer(
JNIEnv *env, jclass); JNIEnv* env, jclass);
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_deleteSLBufferQueueAudioPlayer( Java_com_google_sample_echo_MainActivity_deleteSLBufferQueueAudioPlayer(
JNIEnv *env, jclass type); JNIEnv* env, jclass type);
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
Java_com_google_sample_echo_MainActivity_createAudioRecorder(JNIEnv *env, Java_com_google_sample_echo_MainActivity_createAudioRecorder(JNIEnv* env,
jclass type); jclass type);
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_deleteAudioRecorder(JNIEnv *env, Java_com_google_sample_echo_MainActivity_deleteAudioRecorder(JNIEnv* env,
jclass type); jclass type);
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_startPlay(JNIEnv *env, jclass type); Java_com_google_sample_echo_MainActivity_startPlay(JNIEnv* env, jclass type);
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_sample_echo_MainActivity_stopPlay(JNIEnv *env, jclass type); Java_com_google_sample_echo_MainActivity_stopPlay(JNIEnv* env, jclass type);
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
Java_com_google_sample_echo_MainActivity_configureEcho(JNIEnv *env, jclass type, Java_com_google_sample_echo_MainActivity_configureEcho(JNIEnv* env, jclass type,
jint delayInMs, jint delayInMs,
jfloat decay); jfloat decay);
#ifdef __cplusplus #ifdef __cplusplus

View File

@@ -30,8 +30,8 @@
// semantically, one should either use disallow both or neither. Try to // semantically, one should either use disallow both or neither. Try to
// avoid these in new code. // avoid these in new code.
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName &) = delete; \ TypeName(const TypeName&) = delete; \
void operator=(const TypeName &) = delete void operator=(const TypeName&) = delete
// A macro to disallow all the implicit constructors, namely the // A macro to disallow all the implicit constructors, namely the
// default constructor, copy constructor and operator= functions. // default constructor, copy constructor and operator= functions.

View File

@@ -56,11 +56,11 @@ typedef int32_t Fixed;
#define FIXED_FROM_INT(x) ((x) << FIXED_BITS) #define FIXED_FROM_INT(x) ((x) << FIXED_BITS)
#define FIXED_TO_INT(x) ((x) >> FIXED_BITS) #define FIXED_TO_INT(x) ((x) >> FIXED_BITS)
#define FIXED_FROM_FLOAT(x) ((Fixed)((x)*FIXED_ONE)) #define FIXED_FROM_FLOAT(x) ((Fixed)((x) * FIXED_ONE))
#define FIXED_TO_FLOAT(x) ((x) / (1. * FIXED_ONE)) #define FIXED_TO_FLOAT(x) ((x) / (1. * FIXED_ONE))
#define FIXED_MUL(x, y) (((int64_t)(x) * (y)) >> FIXED_BITS) #define FIXED_MUL(x, y) (((int64_t)(x) * (y)) >> FIXED_BITS)
#define FIXED_DIV(x, y) (((int64_t)(x)*FIXED_ONE) / (y)) #define FIXED_DIV(x, y) (((int64_t)(x) * FIXED_ONE) / (y))
#define FIXED_DIV2(x) ((x) >> 1) #define FIXED_DIV2(x) ((x) >> 1)
#define FIXED_AVERAGE(x, y) (((x) + (y)) >> 1) #define FIXED_AVERAGE(x, y) (((x) + (y)) >> 1)
@@ -83,8 +83,8 @@ typedef int32_t Angle;
#define ANGLE_PI2 (1 << (ANGLE_BITS - 2)) #define ANGLE_PI2 (1 << (ANGLE_BITS - 2))
#define ANGLE_PI4 (1 << (ANGLE_BITS - 3)) #define ANGLE_PI4 (1 << (ANGLE_BITS - 3))
#define ANGLE_FROM_FLOAT(x) (Angle)((x)*ANGLE_PI / M_PI) #define ANGLE_FROM_FLOAT(x) (Angle)((x) * ANGLE_PI / M_PI)
#define ANGLE_TO_FLOAT(x) ((x)*M_PI / ANGLE_PI) #define ANGLE_TO_FLOAT(x) ((x) * M_PI / ANGLE_PI)
#if ANGLE_BITS <= FIXED_BITS #if ANGLE_BITS <= FIXED_BITS
#define ANGLE_FROM_FIXED(x) (Angle)((x) >> (FIXED_BITS - ANGLE_BITS)) #define ANGLE_FROM_FIXED(x) (Angle)((x) >> (FIXED_BITS - ANGLE_BITS))

View File

@@ -66,7 +66,7 @@ extern "C" void android_main(struct android_app* state) {
// loop waiting for stuff to do. // loop waiting for stuff to do.
while (!state->destroyRequested) { while (!state->destroyRequested) {
struct android_poll_source* source = nullptr; struct android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(0, NULL, nullptr, (void**)&source); auto result = ALooper_pollOnce(0, NULL, nullptr, (void**)&source);
ASSERT(result != ALOOPER_POLL_ERROR, "ALooper_pollOnce returned an error"); ASSERT(result != ALOOPER_POLL_ERROR, "ALooper_pollOnce returned an error");
if (source != NULL) { if (source != NULL) {
source->process(state, source); source->process(state, source);

View File

@@ -27,9 +27,9 @@
int CameraEngine::GetDisplayRotation() { int CameraEngine::GetDisplayRotation() {
ASSERT(app_, "Application is not initialized"); ASSERT(app_, "Application is not initialized");
JNIEnv *env; JNIEnv* env;
ANativeActivity *activity = app_->activity; ANativeActivity* activity = app_->activity;
activity->vm->GetEnv((void **)&env, JNI_VERSION_1_6); activity->vm->GetEnv((void**)&env, JNI_VERSION_1_6);
activity->vm->AttachCurrentThread(&env, NULL); activity->vm->AttachCurrentThread(&env, NULL);
@@ -55,7 +55,7 @@ int CameraEngine::GetDisplayRotation() {
*/ */
const int kInitDataLen = 6; const int kInitDataLen = 6;
void CameraEngine::EnableUI(void) { void CameraEngine::EnableUI(void) {
JNIEnv *jni; JNIEnv* jni;
app_->activity->vm->AttachCurrentThread(&jni, NULL); app_->activity->vm->AttachCurrentThread(&jni, NULL);
int64_t range[3]; int64_t range[3];
@@ -91,8 +91,8 @@ void CameraEngine::OnTakePhoto() {
} }
} }
void CameraEngine::OnPhotoTaken(const char *fileName) { void CameraEngine::OnPhotoTaken(const char* fileName) {
JNIEnv *jni; JNIEnv* jni;
app_->activity->vm->AttachCurrentThread(&jni, NULL); app_->activity->vm->AttachCurrentThread(&jni, NULL);
// Default class retrieval // Default class retrieval
@@ -128,14 +128,14 @@ void CameraEngine::OnCameraPermission(jboolean granted) {
*/ */
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_camera_basic_CameraActivity_notifyCameraPermission( Java_com_sample_camera_basic_CameraActivity_notifyCameraPermission(
JNIEnv *env, jclass type, jboolean permission) { JNIEnv* env, jclass type, jboolean permission) {
std::thread permissionHandler(&CameraEngine::OnCameraPermission, std::thread permissionHandler(&CameraEngine::OnCameraPermission,
GetAppEngine(), permission); GetAppEngine(), permission);
permissionHandler.detach(); permissionHandler.detach();
} }
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_camera_basic_CameraActivity_TakePhoto(JNIEnv *env, Java_com_sample_camera_basic_CameraActivity_TakePhoto(JNIEnv* env,
jclass type) { jclass type) {
std::thread takePhotoHandler(&CameraEngine::OnTakePhoto, GetAppEngine()); std::thread takePhotoHandler(&CameraEngine::OnTakePhoto, GetAppEngine());
takePhotoHandler.detach(); takePhotoHandler.detach();
@@ -143,14 +143,14 @@ Java_com_sample_camera_basic_CameraActivity_TakePhoto(JNIEnv *env,
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_camera_basic_CameraActivity_OnExposureChanged( Java_com_sample_camera_basic_CameraActivity_OnExposureChanged(
JNIEnv *env, jobject instance, jlong exposurePercent) { JNIEnv* env, jobject instance, jlong exposurePercent) {
GetAppEngine()->OnCameraParameterChanged(ACAMERA_SENSOR_EXPOSURE_TIME, GetAppEngine()->OnCameraParameterChanged(ACAMERA_SENSOR_EXPOSURE_TIME,
exposurePercent); exposurePercent);
} }
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_camera_basic_CameraActivity_OnSensitivityChanged( Java_com_sample_camera_basic_CameraActivity_OnSensitivityChanged(
JNIEnv *env, jobject instance, jlong sensitivity) { JNIEnv* env, jobject instance, jlong sensitivity) {
GetAppEngine()->OnCameraParameterChanged(ACAMERA_SENSOR_SENSITIVITY, GetAppEngine()->OnCameraParameterChanged(ACAMERA_SENSOR_SENSITIVITY,
sensitivity); sensitivity);
} }

View File

@@ -31,8 +31,8 @@
* File names are incrementally appended an index number as * File names are incrementally appended an index number as
* capture0.jpg, capture1.jpg, capture2.jpg * capture0.jpg, capture1.jpg, capture2.jpg
*/ */
static const char *kDirName = "/sdcard/DCIM/Camera/"; static const char* kDirName = "/sdcard/DCIM/Camera/";
static const char *kFileName = "capture"; static const char* kFileName = "capture";
/** /**
* MAX_BUF_COUNT: * MAX_BUF_COUNT:
@@ -50,14 +50,14 @@ static const char *kFileName = "capture";
* we could release ( skip ) some frames by AImageReader_getNextImage() and * we could release ( skip ) some frames by AImageReader_getNextImage() and
* AImageReader_delete(). * AImageReader_delete().
*/ */
void OnImageCallback(void *ctx, AImageReader *reader) { void OnImageCallback(void* ctx, AImageReader* reader) {
reinterpret_cast<ImageReader *>(ctx)->ImageCallback(reader); reinterpret_cast<ImageReader*>(ctx)->ImageCallback(reader);
} }
/** /**
* Constructor * Constructor
*/ */
ImageReader::ImageReader(ImageFormat *res, enum AIMAGE_FORMATS format) ImageReader::ImageReader(ImageFormat* res, enum AIMAGE_FORMATS format)
: presentRotation_(0), reader_(nullptr) { : presentRotation_(0), reader_(nullptr) {
callback_ = nullptr; callback_ = nullptr;
callbackCtx_ = nullptr; callbackCtx_ = nullptr;
@@ -79,17 +79,17 @@ ImageReader::~ImageReader() {
} }
void ImageReader::RegisterCallback( void ImageReader::RegisterCallback(
void *ctx, std::function<void(void *ctx, const char *fileName)> func) { void* ctx, std::function<void(void* ctx, const char* fileName)> func) {
callbackCtx_ = ctx; callbackCtx_ = ctx;
callback_ = func; callback_ = func;
} }
void ImageReader::ImageCallback(AImageReader *reader) { void ImageReader::ImageCallback(AImageReader* reader) {
int32_t format; int32_t format;
media_status_t status = AImageReader_getFormat(reader, &format); media_status_t status = AImageReader_getFormat(reader, &format);
ASSERT(status == AMEDIA_OK, "Failed to get the media format"); ASSERT(status == AMEDIA_OK, "Failed to get the media format");
if (format == AIMAGE_FORMAT_JPEG) { if (format == AIMAGE_FORMAT_JPEG) {
AImage *image = nullptr; AImage* image = nullptr;
media_status_t status = AImageReader_acquireNextImage(reader, &image); media_status_t status = AImageReader_acquireNextImage(reader, &image);
ASSERT(status == AMEDIA_OK && image, "Image is not available"); ASSERT(status == AMEDIA_OK && image, "Image is not available");
@@ -99,9 +99,9 @@ void ImageReader::ImageCallback(AImageReader *reader) {
} }
} }
ANativeWindow *ImageReader::GetNativeWindow(void) { ANativeWindow* ImageReader::GetNativeWindow(void) {
if (!reader_) return nullptr; if (!reader_) return nullptr;
ANativeWindow *nativeWindow; ANativeWindow* nativeWindow;
media_status_t status = AImageReader_getWindow(reader_, &nativeWindow); media_status_t status = AImageReader_getWindow(reader_, &nativeWindow);
ASSERT(status == AMEDIA_OK, "Could not get ANativeWindow"); ASSERT(status == AMEDIA_OK, "Could not get ANativeWindow");
@@ -113,8 +113,8 @@ ANativeWindow *ImageReader::GetNativeWindow(void) {
* Retrieve the next image in ImageReader's bufferQueue, NOT the last image so * Retrieve the next image in ImageReader's bufferQueue, NOT the last image so
* no image is skipped. Recommended for batch/background processing. * no image is skipped. Recommended for batch/background processing.
*/ */
AImage *ImageReader::GetNextImage(void) { AImage* ImageReader::GetNextImage(void) {
AImage *image; AImage* image;
media_status_t status = AImageReader_acquireNextImage(reader_, &image); media_status_t status = AImageReader_acquireNextImage(reader_, &image);
if (status != AMEDIA_OK) { if (status != AMEDIA_OK) {
return nullptr; return nullptr;
@@ -127,8 +127,8 @@ AImage *ImageReader::GetNextImage(void) {
* Retrieve the last image in ImageReader's bufferQueue, deleting images in * Retrieve the last image in ImageReader's bufferQueue, deleting images in
* in front of it on the queue. Recommended for real-time processing. * in front of it on the queue. Recommended for real-time processing.
*/ */
AImage *ImageReader::GetLatestImage(void) { AImage* ImageReader::GetLatestImage(void) {
AImage *image; AImage* image;
media_status_t status = AImageReader_acquireLatestImage(reader_, &image); media_status_t status = AImageReader_acquireLatestImage(reader_, &image);
if (status != AMEDIA_OK) { if (status != AMEDIA_OK) {
return nullptr; return nullptr;
@@ -140,7 +140,7 @@ AImage *ImageReader::GetLatestImage(void) {
* Delete Image * Delete Image
* @param image {@link AImage} instance to be deleted * @param image {@link AImage} instance to be deleted
*/ */
void ImageReader::DeleteImage(AImage *image) { void ImageReader::DeleteImage(AImage* image) {
if (image) AImage_delete(image); if (image) AImage_delete(image);
} }
@@ -207,7 +207,7 @@ static inline uint32_t YUV2RGB(int nY, int nU, int nV) {
* @param image a {@link AImage} instance, source of image conversion. * @param image a {@link AImage} instance, source of image conversion.
* it will be deleted via {@link AImage_delete} * it will be deleted via {@link AImage_delete}
*/ */
bool ImageReader::DisplayImage(ANativeWindow_Buffer *buf, AImage *image) { bool ImageReader::DisplayImage(ANativeWindow_Buffer* buf, AImage* image) {
ASSERT(buf->format == WINDOW_FORMAT_RGBX_8888 || ASSERT(buf->format == WINDOW_FORMAT_RGBX_8888 ||
buf->format == WINDOW_FORMAT_RGBA_8888, buf->format == WINDOW_FORMAT_RGBA_8888,
"Not supported buffer format"); "Not supported buffer format");
@@ -248,7 +248,7 @@ bool ImageReader::DisplayImage(ANativeWindow_Buffer *buf, AImage *image) {
* Refer to: * Refer to:
* https://mathbits.com/MathBits/TISection/Geometry/Transformations2.htm * https://mathbits.com/MathBits/TISection/Geometry/Transformations2.htm
*/ */
void ImageReader::PresentImage(ANativeWindow_Buffer *buf, AImage *image) { void ImageReader::PresentImage(ANativeWindow_Buffer* buf, AImage* image) {
AImageCropRect srcRect; AImageCropRect srcRect;
AImage_getCropRect(image, &srcRect); AImage_getCropRect(image, &srcRect);
@@ -266,13 +266,13 @@ void ImageReader::PresentImage(ANativeWindow_Buffer *buf, AImage *image) {
int32_t height = MIN(buf->height, (srcRect.bottom - srcRect.top)); int32_t height = MIN(buf->height, (srcRect.bottom - srcRect.top));
int32_t width = MIN(buf->width, (srcRect.right - srcRect.left)); int32_t width = MIN(buf->width, (srcRect.right - srcRect.left));
uint32_t *out = static_cast<uint32_t *>(buf->bits); uint32_t* out = static_cast<uint32_t*>(buf->bits);
for (int32_t y = 0; y < height; y++) { for (int32_t y = 0; y < height; y++) {
const uint8_t *pY = yPixel + yStride * (y + srcRect.top) + srcRect.left; const uint8_t* pY = yPixel + yStride * (y + srcRect.top) + srcRect.left;
int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1); int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1);
const uint8_t *pU = uPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pU = uPixel + uv_row_start + (srcRect.left >> 1);
const uint8_t *pV = vPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pV = vPixel + uv_row_start + (srcRect.left >> 1);
for (int32_t x = 0; x < width; x++) { for (int32_t x = 0; x < width; x++) {
const int32_t uv_offset = (x >> 1) * uvPixelStride; const int32_t uv_offset = (x >> 1) * uvPixelStride;
@@ -287,7 +287,7 @@ void ImageReader::PresentImage(ANativeWindow_Buffer *buf, AImage *image) {
* Converting YUV to RGB * Converting YUV to RGB
* Rotation image anti-clockwise 90 degree -- (x, y) --> (-y, x) * Rotation image anti-clockwise 90 degree -- (x, y) --> (-y, x)
*/ */
void ImageReader::PresentImage90(ANativeWindow_Buffer *buf, AImage *image) { void ImageReader::PresentImage90(ANativeWindow_Buffer* buf, AImage* image) {
AImageCropRect srcRect; AImageCropRect srcRect;
AImage_getCropRect(image, &srcRect); AImage_getCropRect(image, &srcRect);
@@ -305,14 +305,14 @@ void ImageReader::PresentImage90(ANativeWindow_Buffer *buf, AImage *image) {
int32_t height = MIN(buf->width, (srcRect.bottom - srcRect.top)); int32_t height = MIN(buf->width, (srcRect.bottom - srcRect.top));
int32_t width = MIN(buf->height, (srcRect.right - srcRect.left)); int32_t width = MIN(buf->height, (srcRect.right - srcRect.left));
uint32_t *out = static_cast<uint32_t *>(buf->bits); uint32_t* out = static_cast<uint32_t*>(buf->bits);
out += height - 1; out += height - 1;
for (int32_t y = 0; y < height; y++) { for (int32_t y = 0; y < height; y++) {
const uint8_t *pY = yPixel + yStride * (y + srcRect.top) + srcRect.left; const uint8_t* pY = yPixel + yStride * (y + srcRect.top) + srcRect.left;
int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1); int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1);
const uint8_t *pU = uPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pU = uPixel + uv_row_start + (srcRect.left >> 1);
const uint8_t *pV = vPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pV = vPixel + uv_row_start + (srcRect.left >> 1);
for (int32_t x = 0; x < width; x++) { for (int32_t x = 0; x < width; x++) {
const int32_t uv_offset = (x >> 1) * uvPixelStride; const int32_t uv_offset = (x >> 1) * uvPixelStride;
@@ -328,7 +328,7 @@ void ImageReader::PresentImage90(ANativeWindow_Buffer *buf, AImage *image) {
* Converting yuv to RGB * Converting yuv to RGB
* Rotate image 180 degree: (x, y) --> (-x, -y) * Rotate image 180 degree: (x, y) --> (-x, -y)
*/ */
void ImageReader::PresentImage180(ANativeWindow_Buffer *buf, AImage *image) { void ImageReader::PresentImage180(ANativeWindow_Buffer* buf, AImage* image) {
AImageCropRect srcRect; AImageCropRect srcRect;
AImage_getCropRect(image, &srcRect); AImage_getCropRect(image, &srcRect);
@@ -346,14 +346,14 @@ void ImageReader::PresentImage180(ANativeWindow_Buffer *buf, AImage *image) {
int32_t height = MIN(buf->height, (srcRect.bottom - srcRect.top)); int32_t height = MIN(buf->height, (srcRect.bottom - srcRect.top));
int32_t width = MIN(buf->width, (srcRect.right - srcRect.left)); int32_t width = MIN(buf->width, (srcRect.right - srcRect.left));
uint32_t *out = static_cast<uint32_t *>(buf->bits); uint32_t* out = static_cast<uint32_t*>(buf->bits);
out += (height - 1) * buf->stride; out += (height - 1) * buf->stride;
for (int32_t y = 0; y < height; y++) { for (int32_t y = 0; y < height; y++) {
const uint8_t *pY = yPixel + yStride * (y + srcRect.top) + srcRect.left; const uint8_t* pY = yPixel + yStride * (y + srcRect.top) + srcRect.left;
int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1); int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1);
const uint8_t *pU = uPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pU = uPixel + uv_row_start + (srcRect.left >> 1);
const uint8_t *pV = vPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pV = vPixel + uv_row_start + (srcRect.left >> 1);
for (int32_t x = 0; x < width; x++) { for (int32_t x = 0; x < width; x++) {
const int32_t uv_offset = (x >> 1) * uvPixelStride; const int32_t uv_offset = (x >> 1) * uvPixelStride;
@@ -370,7 +370,7 @@ void ImageReader::PresentImage180(ANativeWindow_Buffer *buf, AImage *image) {
* Converting image from YUV to RGB * Converting image from YUV to RGB
* Rotate Image counter-clockwise 270 degree: (x, y) --> (y, x) * Rotate Image counter-clockwise 270 degree: (x, y) --> (y, x)
*/ */
void ImageReader::PresentImage270(ANativeWindow_Buffer *buf, AImage *image) { void ImageReader::PresentImage270(ANativeWindow_Buffer* buf, AImage* image) {
AImageCropRect srcRect; AImageCropRect srcRect;
AImage_getCropRect(image, &srcRect); AImage_getCropRect(image, &srcRect);
@@ -388,13 +388,13 @@ void ImageReader::PresentImage270(ANativeWindow_Buffer *buf, AImage *image) {
int32_t height = MIN(buf->width, (srcRect.bottom - srcRect.top)); int32_t height = MIN(buf->width, (srcRect.bottom - srcRect.top));
int32_t width = MIN(buf->height, (srcRect.right - srcRect.left)); int32_t width = MIN(buf->height, (srcRect.right - srcRect.left));
uint32_t *out = static_cast<uint32_t *>(buf->bits); uint32_t* out = static_cast<uint32_t*>(buf->bits);
for (int32_t y = 0; y < height; y++) { for (int32_t y = 0; y < height; y++) {
const uint8_t *pY = yPixel + yStride * (y + srcRect.top) + srcRect.left; const uint8_t* pY = yPixel + yStride * (y + srcRect.top) + srcRect.left;
int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1); int32_t uv_row_start = uvStride * ((y + srcRect.top) >> 1);
const uint8_t *pU = uPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pU = uPixel + uv_row_start + (srcRect.left >> 1);
const uint8_t *pV = vPixel + uv_row_start + (srcRect.left >> 1); const uint8_t* pV = vPixel + uv_row_start + (srcRect.left >> 1);
for (int32_t x = 0; x < width; x++) { for (int32_t x = 0; x < width; x++) {
const int32_t uv_offset = (x >> 1) * uvPixelStride; const int32_t uv_offset = (x >> 1) * uvPixelStride;
@@ -412,16 +412,16 @@ void ImageReader::SetPresentRotation(int32_t angle) {
* Write out jpeg files to kDirName directory * Write out jpeg files to kDirName directory
* @param image point capture jpg image * @param image point capture jpg image
*/ */
void ImageReader::WriteFile(AImage *image) { void ImageReader::WriteFile(AImage* image) {
int planeCount; int planeCount;
media_status_t status = AImage_getNumberOfPlanes(image, &planeCount); media_status_t status = AImage_getNumberOfPlanes(image, &planeCount);
ASSERT(status == AMEDIA_OK && planeCount == 1, ASSERT(status == AMEDIA_OK && planeCount == 1,
"Error: getNumberOfPlanes() planeCount = %d", planeCount); "Error: getNumberOfPlanes() planeCount = %d", planeCount);
uint8_t *data = nullptr; uint8_t* data = nullptr;
int len = 0; int len = 0;
AImage_getPlaneData(image, 0, &data, &len); AImage_getPlaneData(image, 0, &data, &len);
DIR *dir = opendir(kDirName); DIR* dir = opendir(kDirName);
if (dir) { if (dir) {
closedir(dir); closedir(dir);
} else { } else {
@@ -444,7 +444,7 @@ void ImageReader::WriteFile(AImage *image) {
std::to_string(localTime.tm_hour) + std::to_string(localTime.tm_hour) +
std::to_string(localTime.tm_min) + std::to_string(localTime.tm_min) +
std::to_string(localTime.tm_sec) + ".jpg"; std::to_string(localTime.tm_sec) + ".jpg";
FILE *file = fopen(fileName.c_str(), "wb"); FILE* file = fopen(fileName.c_str(), "wb");
if (file && data && len) { if (file && data && len) {
fwrite(data, 1, len, file); fwrite(data, 1, len, file);
fclose(file); fclose(file);

View File

@@ -34,7 +34,7 @@
* Application object: * Application object:
* the top level camera application object, maintained by native code only * the top level camera application object, maintained by native code only
*/ */
CameraAppEngine *pEngineObj = nullptr; CameraAppEngine* pEngineObj = nullptr;
/** /**
* createCamera() Create application instance and NDK camera object * createCamera() Create application instance and NDK camera object
@@ -50,7 +50,7 @@ CameraAppEngine *pEngineObj = nullptr;
* @return application object instance ( not used in this sample ) * @return application object instance ( not used in this sample )
*/ */
extern "C" JNIEXPORT jlong JNICALL extern "C" JNIEXPORT jlong JNICALL
Java_com_sample_textureview_ViewActivity_createCamera(JNIEnv *env, Java_com_sample_textureview_ViewActivity_createCamera(JNIEnv* env,
jobject instance, jobject instance,
jint width, jint height) { jint width, jint height) {
pEngineObj = new CameraAppEngine(env, instance, width, height); pEngineObj = new CameraAppEngine(env, instance, width, height);
@@ -63,13 +63,13 @@ Java_com_sample_textureview_ViewActivity_createCamera(JNIEnv *env,
* triggers native camera object be released * triggers native camera object be released
*/ */
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_deleteCamera(JNIEnv *env, Java_com_sample_textureview_ViewActivity_deleteCamera(JNIEnv* env,
jobject instance, jobject instance,
jlong ndkCameraObj) { jlong ndkCameraObj) {
if (!pEngineObj || !ndkCameraObj) { if (!pEngineObj || !ndkCameraObj) {
return; return;
} }
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj); CameraAppEngine* pApp = reinterpret_cast<CameraAppEngine*>(ndkCameraObj);
ASSERT(pApp == pEngineObj, "NdkCamera Obj mismatch"); ASSERT(pApp == pEngineObj, "NdkCamera Obj mismatch");
delete pApp; delete pApp;
@@ -91,11 +91,11 @@ Java_com_sample_textureview_ViewActivity_deleteCamera(JNIEnv *env,
*/ */
extern "C" JNIEXPORT jobject JNICALL extern "C" JNIEXPORT jobject JNICALL
Java_com_sample_textureview_ViewActivity_getMinimumCompatiblePreviewSize( Java_com_sample_textureview_ViewActivity_getMinimumCompatiblePreviewSize(
JNIEnv *env, jobject instance, jlong ndkCameraObj) { JNIEnv* env, jobject instance, jlong ndkCameraObj) {
if (!ndkCameraObj) { if (!ndkCameraObj) {
return nullptr; return nullptr;
} }
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj); CameraAppEngine* pApp = reinterpret_cast<CameraAppEngine*>(ndkCameraObj);
jclass cls = env->FindClass("android/util/Size"); jclass cls = env->FindClass("android/util/Size");
jobject previewSize = jobject previewSize =
env->NewObject(cls, env->GetMethodID(cls, "<init>", "(II)V"), env->NewObject(cls, env->GetMethodID(cls, "<init>", "(II)V"),
@@ -111,9 +111,9 @@ Java_com_sample_textureview_ViewActivity_getMinimumCompatiblePreviewSize(
*/ */
extern "C" JNIEXPORT jint JNICALL extern "C" JNIEXPORT jint JNICALL
Java_com_sample_textureview_ViewActivity_getCameraSensorOrientation( Java_com_sample_textureview_ViewActivity_getCameraSensorOrientation(
JNIEnv *env, jobject instance, jlong ndkCameraObj) { JNIEnv* env, jobject instance, jlong ndkCameraObj) {
ASSERT(ndkCameraObj, "NativeObject should not be null Pointer"); ASSERT(ndkCameraObj, "NativeObject should not be null Pointer");
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj); CameraAppEngine* pApp = reinterpret_cast<CameraAppEngine*>(ndkCameraObj);
return pApp->GetCameraSensorOrientation(ACAMERA_LENS_FACING_BACK); return pApp->GetCameraSensorOrientation(ACAMERA_LENS_FACING_BACK);
} }
@@ -125,10 +125,10 @@ Java_com_sample_textureview_ViewActivity_getCameraSensorOrientation(
*/ */
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_onPreviewSurfaceCreated( Java_com_sample_textureview_ViewActivity_onPreviewSurfaceCreated(
JNIEnv *env, jobject instance, jlong ndkCameraObj, jobject surface) { JNIEnv* env, jobject instance, jlong ndkCameraObj, jobject surface) {
ASSERT(ndkCameraObj && (jlong)pEngineObj == ndkCameraObj, ASSERT(ndkCameraObj && (jlong)pEngineObj == ndkCameraObj,
"NativeObject should not be null Pointer"); "NativeObject should not be null Pointer");
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj); CameraAppEngine* pApp = reinterpret_cast<CameraAppEngine*>(ndkCameraObj);
pApp->CreateCameraSession(surface); pApp->CreateCameraSession(surface);
pApp->StartPreview(true); pApp->StartPreview(true);
} }
@@ -141,8 +141,8 @@ Java_com_sample_textureview_ViewActivity_onPreviewSurfaceCreated(
*/ */
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_sample_textureview_ViewActivity_onPreviewSurfaceDestroyed( Java_com_sample_textureview_ViewActivity_onPreviewSurfaceDestroyed(
JNIEnv *env, jobject instance, jlong ndkCameraObj, jobject surface) { JNIEnv* env, jobject instance, jlong ndkCameraObj, jobject surface) {
CameraAppEngine *pApp = reinterpret_cast<CameraAppEngine *>(ndkCameraObj); CameraAppEngine* pApp = reinterpret_cast<CameraAppEngine*>(ndkCameraObj);
ASSERT(ndkCameraObj && pEngineObj == pApp, ASSERT(ndkCameraObj && pEngineObj == pApp,
"NativeObject should not be null Pointer"); "NativeObject should not be null Pointer");
jclass cls = env->FindClass("android/view/Surface"); jclass cls = env->FindClass("android/view/Surface");
@@ -151,11 +151,11 @@ Java_com_sample_textureview_ViewActivity_onPreviewSurfaceDestroyed(
jstring destroyObjStr = jstring destroyObjStr =
reinterpret_cast<jstring>(env->CallObjectMethod(surface, toString)); reinterpret_cast<jstring>(env->CallObjectMethod(surface, toString));
const char *destroyObjName = env->GetStringUTFChars(destroyObjStr, nullptr); const char* destroyObjName = env->GetStringUTFChars(destroyObjStr, nullptr);
jstring appObjStr = reinterpret_cast<jstring>( jstring appObjStr = reinterpret_cast<jstring>(
env->CallObjectMethod(pApp->GetSurfaceObject(), toString)); env->CallObjectMethod(pApp->GetSurfaceObject(), toString));
const char *appObjName = env->GetStringUTFChars(appObjStr, nullptr); const char* appObjName = env->GetStringUTFChars(appObjStr, nullptr);
ASSERT(!strcmp(destroyObjName, appObjName), "object Name MisMatch"); ASSERT(!strcmp(destroyObjName, appObjName), "object Name MisMatch");

View File

@@ -17,7 +17,7 @@
#include "util.hpp" #include "util.hpp"
void RenderBackgroundAnimation(ShapeRenderer *r) { void RenderBackgroundAnimation(ShapeRenderer* r) {
float aspect = SceneManager::GetInstance()->GetScreenAspect(); float aspect = SceneManager::GetInstance()->GetScreenAspect();
static const int BG_RECTS = 50; static const int BG_RECTS = 50;
static const float RECT_W = 0.3f; static const float RECT_W = 0.3f;

View File

@@ -18,14 +18,14 @@
#define GEOM_DEBUG LOGD #define GEOM_DEBUG LOGD
// #define GEOM_DEBUG // #define GEOM_DEBUG
SimpleGeom *AsciiArtToGeom(const char *art, float scale) { SimpleGeom* AsciiArtToGeom(const char* art, float scale) {
// figure out width and height // figure out width and height
LOGD("Creating geometry from ASCII art."); LOGD("Creating geometry from ASCII art.");
GEOM_DEBUG("Ascii art source:\n%s", art); GEOM_DEBUG("Ascii art source:\n%s", art);
int rows = 1; int rows = 1;
int curCols = 0, cols = 0; int curCols = 0, cols = 0;
int r, c; int r, c;
const char *p; const char* p;
for (p = art; *p; ++p) { for (p = art; *p; ++p) {
if (*p == '\n') { if (*p == '\n') {
rows++; rows++;
@@ -40,7 +40,7 @@ SimpleGeom *AsciiArtToGeom(const char *art, float scale) {
GEOM_DEBUG("Making working array."); GEOM_DEBUG("Making working array.");
// allocate a rows x cols array that we will use as working space // allocate a rows x cols array that we will use as working space
unsigned int **v = new unsigned int *[rows]; unsigned int** v = new unsigned int*[rows];
for (r = 0; r < rows; r++) { for (r = 0; r < rows; r++) {
v[r] = new unsigned int[cols]; v[r] = new unsigned int[cols];
memset(v[r], 0, cols * sizeof(unsigned int)); memset(v[r], 0, cols * sizeof(unsigned int));
@@ -97,8 +97,8 @@ SimpleGeom *AsciiArtToGeom(const char *art, float scale) {
// allocate arrays for the vertices and lines // allocate arrays for the vertices and lines
const int VERTICES_STRIDE = sizeof(GLfloat) * 7; const int VERTICES_STRIDE = sizeof(GLfloat) * 7;
const int VERTICES_COLOR_OFFSET = sizeof(GLfloat) * 3; const int VERTICES_COLOR_OFFSET = sizeof(GLfloat) * 3;
GLfloat *verticesArray = new GLfloat[vertices * VERTICES_STRIDE]; GLfloat* verticesArray = new GLfloat[vertices * VERTICES_STRIDE];
GLushort *indicesArray = new GLushort[indices]; GLushort* indicesArray = new GLushort[indices];
vertices = indices = 0; // current count of vertices and lines vertices = indices = 0; // current count of vertices and lines
float left = (-cols / 2) * scale; float left = (-cols / 2) * scale;
@@ -216,7 +216,7 @@ SimpleGeom *AsciiArtToGeom(const char *art, float scale) {
// create the buffers // create the buffers
GEOM_DEBUG("Creating output VBO (%d vertices) and IBO (%d indices).", GEOM_DEBUG("Creating output VBO (%d vertices) and IBO (%d indices).",
vertices, indices); vertices, indices);
SimpleGeom *out = new SimpleGeom( SimpleGeom* out = new SimpleGeom(
new VertexBuf(verticesArray, vertices * sizeof(GLfloat) * VERTICES_STRIDE, new VertexBuf(verticesArray, vertices * sizeof(GLfloat) * VERTICES_STRIDE,
VERTICES_STRIDE), VERTICES_STRIDE),
new IndexBuf(indicesArray, indices * sizeof(GLushort))); new IndexBuf(indicesArray, indices * sizeof(GLushort)));

View File

@@ -42,7 +42,7 @@ DialogScene::DialogScene() {
DialogScene::~DialogScene() {} DialogScene::~DialogScene() {}
void DialogScene::CreateWidgetsSetText() { void DialogScene::CreateWidgetsSetText() {
const char *text = mText; const char* text = mText;
float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect(); float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect();
if (mTextBoxId < 0) { if (mTextBoxId < 0) {
@@ -59,7 +59,7 @@ void DialogScene::CreateWidgetsSetText() {
} }
void DialogScene::CreateWidgetsSingleButton() { void DialogScene::CreateWidgetsSingleButton() {
const char *text = mLeftButtonText; const char* text = mLeftButtonText;
int action = mLeftButtonAction; int action = mLeftButtonAction;
float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect(); float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect();
mLeftButtonId = NewWidget() mLeftButtonId = NewWidget()
@@ -77,9 +77,9 @@ void DialogScene::CreateWidgetsSingleButton() {
} }
void DialogScene::CreateWidgetsTwoButtons() { void DialogScene::CreateWidgetsTwoButtons() {
const char *leftText = mLeftButtonText; const char* leftText = mLeftButtonText;
int leftAction = mLeftButtonAction; int leftAction = mLeftButtonAction;
const char *rightText = mRightButtonText; const char* rightText = mRightButtonText;
int rightAction = mRightButtonAction; int rightAction = mRightButtonAction;
float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect(); float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect();
@@ -131,13 +131,13 @@ void DialogScene::RenderBackground() {
} }
bool DialogScene::OnBackKeyPressed() { bool DialogScene::OnBackKeyPressed() {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
mgr->RequestNewScene(new WelcomeScene()); mgr->RequestNewScene(new WelcomeScene());
return true; return true;
} }
void DialogScene::OnButtonClicked(int id) { void DialogScene::OnButtonClicked(int id) {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
int action; int action;
if (id == mLeftButtonId) { if (id == mLeftButtonId) {

View File

@@ -15,7 +15,7 @@
*/ */
#include "indexbuf.hpp" #include "indexbuf.hpp"
IndexBuf::IndexBuf(GLushort *data, int dataSizeBytes) { IndexBuf::IndexBuf(GLushort* data, int dataSizeBytes) {
mCount = dataSizeBytes / sizeof(GLushort); mCount = dataSizeBytes / sizeof(GLushort);
glGenBuffers(1, &mIbo); glGenBuffers(1, &mIbo);

View File

@@ -43,7 +43,7 @@ static void _init() {
_init_done = true; _init_done = true;
// look up the AMotionEvent_getAxisValue function // look up the AMotionEvent_getAxisValue function
void *lib_android; void* lib_android;
LOGD("Trying to dlopen libandroid.so"); LOGD("Trying to dlopen libandroid.so");
if ((lib_android = dlopen("libandroid.so", 0))) { if ((lib_android = dlopen("libandroid.so", 0))) {
LOGD("Opened libandroid.so, looking for AMotionEvent_getAxisValue."); LOGD("Opened libandroid.so, looking for AMotionEvent_getAxisValue.");
@@ -105,7 +105,7 @@ static void _report_key_states_from_axes(float x, float y,
_report_key_state(OURKEY_DOWN, y > 0.5f, callback); _report_key_state(OURKEY_DOWN, y > 0.5f, callback);
} }
static bool _process_keys(bool isJoy, AInputEvent *event, static bool _process_keys(bool isJoy, AInputEvent* event,
CookedEventCallback callback) { CookedEventCallback callback) {
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) { if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) {
int action = AKeyEvent_getAction(event); int action = AKeyEvent_getAction(event);
@@ -138,12 +138,12 @@ static bool _process_keys(bool isJoy, AInputEvent *event,
return false; return false;
} }
static void _look_up_motion_range(int deviceId, int source, float *outMinX, static void _look_up_motion_range(int deviceId, int source, float* outMinX,
float *outMaxX, float *outMinY, float* outMaxX, float* outMinY,
float *outMaxY) { float* outMaxY) {
int i; int i;
for (i = 0; i < _motion_range_cache_items; i++) { for (i = 0; i < _motion_range_cache_items; i++) {
DeviceMotionRange *item = &_motion_range_cache[i]; DeviceMotionRange* item = &_motion_range_cache[i];
if (item->deviceId == deviceId && item->source == source) { if (item->deviceId == deviceId && item->source == source) {
*outMinX = item->minX; *outMinX = item->minX;
*outMaxX = item->maxX; *outMaxX = item->maxX;
@@ -153,7 +153,7 @@ static void _look_up_motion_range(int deviceId, int source, float *outMinX,
} }
} }
DeviceMotionRange *newItem; DeviceMotionRange* newItem;
if (_motion_range_cache_items >= MOTION_RANGE_CACHE_MAX) { if (_motion_range_cache_items >= MOTION_RANGE_CACHE_MAX) {
static bool warned = false; static bool warned = false;
if (!warned) { if (!warned) {
@@ -191,7 +191,7 @@ static void _look_up_motion_range(int deviceId, int source, float *outMinX,
*outMaxY = newItem->maxY; *outMaxY = newItem->maxY;
} }
static bool CookEvent_Joy(AInputEvent *event, CookedEventCallback callback) { static bool CookEvent_Joy(AInputEvent* event, CookedEventCallback callback) {
struct CookedEvent ev; struct CookedEvent ev;
memset(&ev, 0, sizeof(ev)); memset(&ev, 0, sizeof(ev));
ev.type = COOKED_EVENT_TYPE_JOY; ev.type = COOKED_EVENT_TYPE_JOY;
@@ -201,7 +201,7 @@ static bool CookEvent_Joy(AInputEvent *event, CookedEventCallback callback) {
return callback(&ev); return callback(&ev);
} }
static bool CookEvent_Motion(AInputEvent *event, CookedEventCallback callback) { static bool CookEvent_Motion(AInputEvent* event, CookedEventCallback callback) {
int src = AInputEvent_getSource(event); int src = AInputEvent_getSource(event);
int action = AMotionEvent_getAction(event); int action = AMotionEvent_getAction(event);
int actionMasked = action & AMOTION_EVENT_ACTION_MASK; int actionMasked = action & AMOTION_EVENT_ACTION_MASK;
@@ -258,7 +258,7 @@ static bool CookEvent_Motion(AInputEvent *event, CookedEventCallback callback) {
return (src != SOURCE_TOUCH_NAVIGATION); return (src != SOURCE_TOUCH_NAVIGATION);
} }
bool CookEvent(AInputEvent *event, CookedEventCallback callback) { bool CookEvent(AInputEvent* event, CookedEventCallback callback) {
int type = AInputEvent_getType(event); int type = AInputEvent_getType(event);
int src = AInputEvent_getSource(event); int src = AInputEvent_getSource(event);
bool isJoy = (type == AINPUT_EVENT_TYPE_MOTION) && bool isJoy = (type == AINPUT_EVENT_TYPE_MOTION) &&

View File

@@ -33,12 +33,12 @@
// max # of GL errors to print before giving up // max # of GL errors to print before giving up
#define MAX_GL_ERRORS 200 #define MAX_GL_ERRORS 200
static NativeEngine *_singleton = NULL; static NativeEngine* _singleton = NULL;
// workaround for internal bug b/149866792 // workaround for internal bug b/149866792
static NativeEngineSavedState appState = {false}; static NativeEngineSavedState appState = {false};
NativeEngine::NativeEngine(struct android_app *app) { NativeEngine::NativeEngine(struct android_app* app) {
LOGD("NativeEngine: initializing."); LOGD("NativeEngine: initializing.");
mApp = app; mApp = app;
mHasFocus = mIsVisible = mHasWindow = false; mHasFocus = mIsVisible = mHasWindow = false;
@@ -55,7 +55,7 @@ NativeEngine::NativeEngine(struct android_app *app) {
if (app->savedState != NULL) { if (app->savedState != NULL) {
// we are starting with previously saved state -- restore it // we are starting with previously saved state -- restore it
mState = *(struct NativeEngineSavedState *)app->savedState; mState = *(struct NativeEngineSavedState*)app->savedState;
} }
// only one instance of NativeEngine may exist! // only one instance of NativeEngine may exist!
@@ -66,7 +66,7 @@ NativeEngine::NativeEngine(struct android_app *app) {
LOGD("NativeEngine: API version %d.", mApiVersion); LOGD("NativeEngine: API version %d.", mApiVersion);
} }
NativeEngine *NativeEngine::GetInstance() { NativeEngine* NativeEngine::GetInstance() {
MY_ASSERT(_singleton != NULL); MY_ASSERT(_singleton != NULL);
return _singleton; return _singleton;
} }
@@ -83,13 +83,13 @@ NativeEngine::~NativeEngine() {
_singleton = NULL; _singleton = NULL;
} }
static void _handle_cmd_proxy(struct android_app *app, int32_t cmd) { static void _handle_cmd_proxy(struct android_app* app, int32_t cmd) {
NativeEngine *engine = (NativeEngine *)app->userData; NativeEngine* engine = (NativeEngine*)app->userData;
engine->HandleCommand(cmd); engine->HandleCommand(cmd);
} }
static int _handle_input_proxy(struct android_app *app, AInputEvent *event) { static int _handle_input_proxy(struct android_app* app, AInputEvent* event) {
NativeEngine *engine = (NativeEngine *)app->userData; NativeEngine* engine = (NativeEngine*)app->userData;
return engine->HandleInput(event) ? 1 : 0; return engine->HandleInput(event) ? 1 : 0;
} }
@@ -104,9 +104,9 @@ void NativeEngine::GameLoop() {
while (!mApp->destroyRequested) { while (!mApp->destroyRequested) {
// If not animating, block until we get an event; if animating, don't block. // If not animating, block until we get an event; if animating, don't block.
struct android_poll_source *source = nullptr; struct android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(IsAnimating() ? 0 : -1, NULL, nullptr, auto result = ALooper_pollOnce(IsAnimating() ? 0 : -1, NULL, nullptr,
(void **)&source); (void**)&source);
MY_ASSERT(result != ALOOPER_POLL_ERROR); MY_ASSERT(result != ALOOPER_POLL_ERROR);
// process event // process event
if (source != NULL) { if (source != NULL) {
@@ -119,7 +119,7 @@ void NativeEngine::GameLoop() {
} }
} }
JNIEnv *NativeEngine::GetJniEnv() { JNIEnv* NativeEngine::GetJniEnv() {
if (!mJniEnv) { if (!mJniEnv) {
LOGD("Attaching current thread to JNI."); LOGD("Attaching current thread to JNI.");
if (0 != mApp->activity->vm->AttachCurrentThread(&mJniEnv, NULL)) { if (0 != mApp->activity->vm->AttachCurrentThread(&mJniEnv, NULL)) {
@@ -134,7 +134,7 @@ JNIEnv *NativeEngine::GetJniEnv() {
} }
void NativeEngine::HandleCommand(int32_t cmd) { void NativeEngine::HandleCommand(int32_t cmd) {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
VLOGD("NativeEngine: handling command %d.", cmd); VLOGD("NativeEngine: handling command %d.", cmd);
switch (cmd) { switch (cmd) {
@@ -143,7 +143,7 @@ void NativeEngine::HandleCommand(int32_t cmd) {
VLOGD("NativeEngine: APP_CMD_SAVE_STATE"); VLOGD("NativeEngine: APP_CMD_SAVE_STATE");
mState.mHasFocus = mHasFocus; mState.mHasFocus = mHasFocus;
mApp->savedState = malloc(sizeof(mState)); mApp->savedState = malloc(sizeof(mState));
*((NativeEngineSavedState *)mApp->savedState) = mState; *((NativeEngineSavedState*)mApp->savedState) = mState;
mApp->savedStateSize = sizeof(mState); mApp->savedStateSize = sizeof(mState);
break; break;
case APP_CMD_INIT_WINDOW: case APP_CMD_INIT_WINDOW:
@@ -153,7 +153,7 @@ void NativeEngine::HandleCommand(int32_t cmd) {
mHasWindow = true; mHasWindow = true;
if (mApp->savedStateSize == sizeof(mState) && if (mApp->savedStateSize == sizeof(mState) &&
mApp->savedState != nullptr) { mApp->savedState != nullptr) {
mState = *((NativeEngineSavedState *)mApp->savedState); mState = *((NativeEngineSavedState*)mApp->savedState);
mHasFocus = mState.mHasFocus; mHasFocus = mState.mHasFocus;
} else { } else {
// Workaround APP_CMD_GAINED_FOCUS issue where the focus state is not // Workaround APP_CMD_GAINED_FOCUS issue where the focus state is not
@@ -225,8 +225,8 @@ void NativeEngine::HandleCommand(int32_t cmd) {
mEglContext, mEglConfig); mEglContext, mEglConfig);
} }
static bool _cooked_event_callback(struct CookedEvent *event) { static bool _cooked_event_callback(struct CookedEvent* event) {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
PointerCoords coords; PointerCoords coords;
memset(&coords, 0, sizeof(coords)); memset(&coords, 0, sizeof(coords));
coords.x = event->motionX; coords.x = event->motionX;
@@ -263,7 +263,7 @@ static bool _cooked_event_callback(struct CookedEvent *event) {
} }
} }
bool NativeEngine::HandleInput(AInputEvent *event) { bool NativeEngine::HandleInput(AInputEvent* event) {
return CookEvent(event, _cooked_event_callback); return CookEvent(event, _cooked_event_callback);
} }
@@ -410,7 +410,7 @@ bool NativeEngine::PrepareToRender() {
void NativeEngine::KillGLObjects() { void NativeEngine::KillGLObjects() {
if (mHasGLObjects) { if (mHasGLObjects) {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
mgr->KillGraphics(); mgr->KillGraphics();
mHasGLObjects = false; mHasGLObjects = false;
} }
@@ -516,7 +516,7 @@ void NativeEngine::DoFrame() {
return; return;
} }
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
// how big is the surface? We query every frame because it's cheap, and some // how big is the surface? We query every frame because it's cheap, and some
// strange devices out there change the surface size without calling any // strange devices out there change the surface size without calling any
@@ -565,11 +565,11 @@ void NativeEngine::DoFrame() {
} }
} }
android_app *NativeEngine::GetAndroidApp() { return mApp; } android_app* NativeEngine::GetAndroidApp() { return mApp; }
bool NativeEngine::InitGLObjects() { bool NativeEngine::InitGLObjects() {
if (!mHasGLObjects) { if (!mHasGLObjects) {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
mgr->StartGraphics(); mgr->StartGraphics();
_log_opengl_error(glGetError()); _log_opengl_error(glGetError());
mHasGLObjects = true; mHasGLObjects = true;

View File

@@ -18,7 +18,7 @@
#include "game_consts.hpp" #include "game_consts.hpp"
void ObstacleGenerator::Generate(Obstacle *result) { void ObstacleGenerator::Generate(Obstacle* result) {
static const int PROB_TABLE[] = { static const int PROB_TABLE[] = {
// EASY MED INT HARD // EASY MED INT HARD
100, 0, 0, 0, // difficulty 0 100, 0, 0, 0, // difficulty 0
@@ -55,22 +55,22 @@ void ObstacleGenerator::Generate(Obstacle *result) {
result->PutRandomBonus(); result->PutRandomBonus();
} }
void ObstacleGenerator::FillRow(Obstacle *result, int row) { void ObstacleGenerator::FillRow(Obstacle* result, int row) {
for (int i = 0; i < OBS_GRID_SIZE; ++i) { for (int i = 0; i < OBS_GRID_SIZE; ++i) {
result->grid[i][row] = true; result->grid[i][row] = true;
} }
} }
void ObstacleGenerator::FillCol(Obstacle *result, int col) { void ObstacleGenerator::FillCol(Obstacle* result, int col) {
for (int i = 0; i < OBS_GRID_SIZE; ++i) { for (int i = 0; i < OBS_GRID_SIZE; ++i) {
result->grid[col][i] = true; result->grid[col][i] = true;
} }
} }
void ObstacleGenerator::GenEasy(Obstacle *result) { void ObstacleGenerator::GenEasy(Obstacle* result) {
int n = Random(4); int n = Random(4);
int i, j; int i, j;
Obstacle *o = result; // shorthand Obstacle* o = result; // shorthand
switch (n) { switch (n) {
case 0: case 0:
i = Random(1, OBS_GRID_SIZE - 1); // i is the row of the bonus i = Random(1, OBS_GRID_SIZE - 1); // i is the row of the bonus
@@ -95,7 +95,7 @@ void ObstacleGenerator::GenEasy(Obstacle *result) {
} }
} }
void ObstacleGenerator::GenMedium(Obstacle *result) { void ObstacleGenerator::GenMedium(Obstacle* result) {
int n = Random(3); int n = Random(3);
int i; int i;
switch (n) { switch (n) {
@@ -117,7 +117,7 @@ void ObstacleGenerator::GenMedium(Obstacle *result) {
} }
} }
void ObstacleGenerator::GenIntermediate(Obstacle *result) { void ObstacleGenerator::GenIntermediate(Obstacle* result) {
int n = Random(3); int n = Random(3);
int i; int i;
switch (n) { switch (n) {
@@ -142,7 +142,7 @@ void ObstacleGenerator::GenIntermediate(Obstacle *result) {
} }
} }
void ObstacleGenerator::GenHard(Obstacle *result) { void ObstacleGenerator::GenHard(Obstacle* result) {
int n = Random(4); int n = Random(4);
int i; int i;
int j; int j;

View File

@@ -40,7 +40,7 @@ static const float OBS_COLORS[] = {0.0f, 0.0f, 0.0f, // style 0 (not used)
0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f}; 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f};
static const char *TONE_BONUS[] = { static const char* TONE_BONUS[] = {
"d70 f150. f250. f350. f450.", "d70 f200. f300. f400. f500.", "d70 f150. f250. f350. f450.", "d70 f200. f300. f400. f500.",
"d70 f250. f350. f450. f550.", "d70 f300. f400. f500. f600.", "d70 f250. f350. f450. f550.", "d70 f300. f400. f500. f600.",
"d70 f350. f450. f550. f650.", "d70 f400. f500. f600. f700.", "d70 f350. f450. f550. f650.", "d70 f400. f500. f600. f700.",
@@ -111,7 +111,7 @@ PlayScene::PlayScene() : Scene() {
/* /*
* where do I put the program??? * where do I put the program???
*/ */
const char *savePath = "/mnt/sdcard/com.google.example.games.tunnel.fix"; const char* savePath = "/mnt/sdcard/com.google.example.games.tunnel.fix";
int len = strlen(savePath) + strlen(SAVE_FILE_NAME) + 3; int len = strlen(savePath) + strlen(SAVE_FILE_NAME) + 3;
mSaveFileName = new char[len]; mSaveFileName = new char[len];
strcpy(mSaveFileName, savePath); strcpy(mSaveFileName, savePath);
@@ -132,7 +132,7 @@ void PlayScene::LoadProgress() {
mSavedCheckpoint = 0; mSavedCheckpoint = 0;
LOGD("Attempting to load: %s", mSaveFileName); LOGD("Attempting to load: %s", mSaveFileName);
FILE *f = fopen(mSaveFileName, "r"); FILE* f = fopen(mSaveFileName, "r");
bool hasLocalFile = false; bool hasLocalFile = false;
if (f) { if (f) {
hasLocalFile = true; hasLocalFile = true;
@@ -174,7 +174,7 @@ void PlayScene::LoadProgress() {
void PlayScene::WriteSaveFile(int level) { void PlayScene::WriteSaveFile(int level) {
LOGD("Saving progress (level %d) to file: %s", level, mSaveFileName); LOGD("Saving progress (level %d) to file: %s", level, mSaveFileName);
FILE *f = fopen(mSaveFileName, "w"); FILE* f = fopen(mSaveFileName, "w");
if (!f) { if (!f) {
LOGE("Error writing to save game file."); LOGE("Error writing to save game file.");
return; return;
@@ -215,9 +215,9 @@ void PlayScene::SaveProgress() {
mCheckpointSignPending = true; mCheckpointSignPending = true;
} }
static unsigned char *_gen_wall_texture() { static unsigned char* _gen_wall_texture() {
static unsigned char pixel_data[WALL_TEXTURE_SIZE * WALL_TEXTURE_SIZE * 3]; static unsigned char pixel_data[WALL_TEXTURE_SIZE * WALL_TEXTURE_SIZE * 3];
unsigned char *p; unsigned char* p;
int x, y; int x, y;
for (y = 0, p = pixel_data; y < WALL_TEXTURE_SIZE; y++) { for (y = 0, p = pixel_data; y < WALL_TEXTURE_SIZE; y++) {
for (x = 0; x < WALL_TEXTURE_SIZE; x++, p += 3) { for (x = 0; x < WALL_TEXTURE_SIZE; x++, p += 3) {
@@ -413,7 +413,7 @@ static float GetSectionEndY(int i) {
return GetSectionCenterY(i) + 0.5f * TUNNEL_SECTION_LENGTH; return GetSectionCenterY(i) + 0.5f * TUNNEL_SECTION_LENGTH;
} }
static void _get_obs_color(int style, float *r, float *g, float *b) { static void _get_obs_color(int style, float* r, float* g, float* b) {
style = Clamp(style, 1, 6); style = Clamp(style, 1, 6);
*r = OBS_COLORS[style * 3]; *r = OBS_COLORS[style * 3];
*g = OBS_COLORS[style * 3 + 1]; *g = OBS_COLORS[style * 3 + 1];
@@ -433,7 +433,7 @@ void PlayScene::RenderTunnel() {
modelMat = glm::translate(glm::mat4(1.0), glm::vec3(0.0, segCenterY, 0.0)); modelMat = glm::translate(glm::mat4(1.0), glm::vec3(0.0, segCenterY, 0.0));
mvpMat = mProjMat * mViewMat * modelMat; mvpMat = mProjMat * mViewMat * modelMat;
Obstacle *o = oi >= mObstacleCount ? NULL : GetObstacleAt(oi); Obstacle* o = oi >= mObstacleCount ? NULL : GetObstacleAt(oi);
// the point light is given in model coordinates, which is 0,0,0 is ok // the point light is given in model coordinates, which is 0,0,0 is ok
// (center of tunnel section) // (center of tunnel section)
@@ -463,7 +463,7 @@ void PlayScene::RenderObstacles() {
mOurShader->SetTexture(mWallTexture); mOurShader->SetTexture(mWallTexture);
for (i = 0; i < mObstacleCount; i++) { for (i = 0; i < mObstacleCount; i++) {
Obstacle *o = GetObstacleAt(i); Obstacle* o = GetObstacleAt(i);
float posY = GetSectionCenterY(mFirstSection + i); float posY = GetSectionCenterY(mFirstSection + i);
if (o->style == Obstacle::STYLE_NULL) { if (o->style == Obstacle::STYLE_NULL) {
@@ -549,7 +549,7 @@ void PlayScene::UpdateMenuSelFromTouch(float x, float y) {
} }
void PlayScene::OnPointerDown(int pointerId, void PlayScene::OnPointerDown(int pointerId,
const struct PointerCoords *coords) { const struct PointerCoords* coords) {
float x = coords->x, y = coords->y; float x = coords->x, y = coords->y;
if (mMenu) { if (mMenu) {
if (coords->isScreen) { if (coords->isScreen) {
@@ -566,7 +566,7 @@ void PlayScene::OnPointerDown(int pointerId,
} }
} }
void PlayScene::OnPointerUp(int pointerId, const struct PointerCoords *coords) { void PlayScene::OnPointerUp(int pointerId, const struct PointerCoords* coords) {
if (mMenu && mMenuTouchActive) { if (mMenu && mMenuTouchActive) {
if (coords->isScreen) { if (coords->isScreen) {
mMenuTouchActive = false; mMenuTouchActive = false;
@@ -578,7 +578,7 @@ void PlayScene::OnPointerUp(int pointerId, const struct PointerCoords *coords) {
} }
void PlayScene::OnPointerMove(int pointerId, void PlayScene::OnPointerMove(int pointerId,
const struct PointerCoords *coords) { const struct PointerCoords* coords) {
float rangeY = coords->isScreen float rangeY = coords->isScreen
? SceneManager::GetInstance()->GetScreenHeight() ? SceneManager::GetInstance()->GetScreenHeight()
: (coords->maxY - coords->minY); : (coords->maxY - coords->minY);
@@ -678,7 +678,7 @@ void PlayScene::RenderMenu() {
} }
void PlayScene::DetectCollisions(float previousY) { void PlayScene::DetectCollisions(float previousY) {
Obstacle *o = GetObstacleAt(0); Obstacle* o = GetObstacleAt(0);
float obsCenter = GetSectionCenterY(mFirstSection); float obsCenter = GetSectionCenterY(mFirstSection);
float obsMin = obsCenter - OBS_BOX_SIZE; float obsMin = obsCenter - OBS_BOX_SIZE;
float curY = mPlayerPos.y; float curY = mPlayerPos.y;
@@ -734,8 +734,8 @@ void PlayScene::DetectCollisions(float previousY) {
} else { } else {
int tone = (score % SCORE_PER_LEVEL) / BONUS_POINTS - 1; int tone = (score % SCORE_PER_LEVEL) / BONUS_POINTS - 1;
tone = tone < 0 ? 0 tone = tone < 0 ? 0
: tone >= static_cast<int>(sizeof(TONE_BONUS) / sizeof(char *)) : tone >= static_cast<int>(sizeof(TONE_BONUS) / sizeof(char*))
? static_cast<int>(sizeof(TONE_BONUS) / sizeof(char *) - 1) ? static_cast<int>(sizeof(TONE_BONUS) / sizeof(char*) - 1)
: tone; : tone;
SfxMan::GetInstance()->PlayTone(TONE_BONUS[tone]); SfxMan::GetInstance()->PlayTone(TONE_BONUS[tone]);
} }
@@ -872,7 +872,7 @@ void PlayScene::OnScreenResized(int width, int height) {
} }
void PlayScene::UpdateProjectionMatrix() { void PlayScene::UpdateProjectionMatrix() {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
mProjMat = glm::perspective(RENDER_FOV, mgr->GetScreenAspect(), mProjMat = glm::perspective(RENDER_FOV, mgr->GetScreenAspect(),
RENDER_NEAR_CLIP, RENDER_FAR_CLIP); RENDER_NEAR_CLIP, RENDER_FAR_CLIP);
} }

View File

@@ -32,12 +32,12 @@ SceneManager::SceneManager() {
mHasGraphics = false; mHasGraphics = false;
} }
void SceneManager::RequestNewScene(Scene *newScene) { void SceneManager::RequestNewScene(Scene* newScene) {
LOGD("SceneManager: requesting new scene %p", newScene); LOGD("SceneManager: requesting new scene %p", newScene);
mSceneToInstall = newScene; mSceneToInstall = newScene;
} }
void SceneManager::InstallScene(Scene *newScene) { void SceneManager::InstallScene(Scene* newScene) {
LOGD("SceneManager: installing scene %p.", newScene); LOGD("SceneManager: installing scene %p.", newScene);
// kill graphics, if we have them. // kill graphics, if we have them.
@@ -65,7 +65,7 @@ void SceneManager::InstallScene(Scene *newScene) {
} }
} }
Scene *SceneManager::GetScene() { return mCurScene; } Scene* SceneManager::GetScene() { return mCurScene; }
void SceneManager::DoFrame() { void SceneManager::DoFrame() {
if (mSceneToInstall) { if (mSceneToInstall) {
@@ -110,24 +110,24 @@ void SceneManager::SetScreenSize(int width, int height) {
} }
} }
SceneManager *SceneManager::GetInstance() { return &_sceneManager; } SceneManager* SceneManager::GetInstance() { return &_sceneManager; }
void SceneManager::OnPointerDown(int pointerId, void SceneManager::OnPointerDown(int pointerId,
const struct PointerCoords *coords) { const struct PointerCoords* coords) {
if (mHasGraphics && mCurScene) { if (mHasGraphics && mCurScene) {
mCurScene->OnPointerDown(pointerId, coords); mCurScene->OnPointerDown(pointerId, coords);
} }
} }
void SceneManager::OnPointerUp(int pointerId, void SceneManager::OnPointerUp(int pointerId,
const struct PointerCoords *coords) { const struct PointerCoords* coords) {
if (mHasGraphics && mCurScene) { if (mHasGraphics && mCurScene) {
mCurScene->OnPointerUp(pointerId, coords); mCurScene->OnPointerUp(pointerId, coords);
} }
} }
void SceneManager::OnPointerMove(int pointerId, void SceneManager::OnPointerMove(int pointerId,
const struct PointerCoords *coords) { const struct PointerCoords* coords) {
if (mHasGraphics && mCurScene) { if (mHasGraphics && mCurScene) {
mCurScene->OnPointerMove(pointerId, coords); mCurScene->OnPointerMove(pointerId, coords);
} }

View File

@@ -21,15 +21,15 @@
#define BUF_SAMPLES_MAX SAMPLES_PER_SEC * 5 // 5 seconds #define BUF_SAMPLES_MAX SAMPLES_PER_SEC * 5 // 5 seconds
#define DEFAULT_VOLUME 0.9f #define DEFAULT_VOLUME 0.9f
static SfxMan *_instance = new SfxMan(); static SfxMan* _instance = new SfxMan();
static short _sample_buf[BUF_SAMPLES_MAX]; static short _sample_buf[BUF_SAMPLES_MAX];
static volatile bool _bufferActive = false; static volatile bool _bufferActive = false;
SfxMan *SfxMan::GetInstance() { SfxMan* SfxMan::GetInstance() {
return _instance ? _instance : (_instance = new SfxMan()); return _instance ? _instance : (_instance = new SfxMan());
} }
static bool _checkError(SLresult r, const char *what) { static bool _checkError(SLresult r, const char* what) {
if (r != SL_RESULT_SUCCESS) { if (r != SL_RESULT_SUCCESS) {
LOGW("SfxMan: Error %s (result %lu)", what, (long unsigned int)r); LOGW("SfxMan: Error %s (result %lu)", what, (long unsigned int)r);
LOGW("DISABLING SOUND!"); LOGW("DISABLING SOUND!");
@@ -38,7 +38,7 @@ static bool _checkError(SLresult r, const char *what) {
return false; return false;
} }
static void _bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { static void _bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* context) {
_bufferActive = false; _bufferActive = false;
} }
@@ -166,7 +166,7 @@ SfxMan::SfxMan() {
bool SfxMan::IsIdle() { return !_bufferActive; } bool SfxMan::IsIdle() { return !_bufferActive; }
static const char *_parseInt(const char *s, int *result) { static const char* _parseInt(const char* s, int* result) {
*result = 0; *result = 0;
while (*s >= '0' && *s <= '9') { while (*s >= '0' && *s <= '9') {
*result = *result * 10 + (*s - '0'); *result = *result * 10 + (*s - '0');
@@ -176,7 +176,7 @@ static const char *_parseInt(const char *s, int *result) {
} }
static int _synth(int frequency, int duration, float amplitude, static int _synth(int frequency, int duration, float amplitude,
short *sample_buf, int samples) { short* sample_buf, int samples) {
int i; int i;
for (i = 0; i < samples; i++) { for (i = 0; i < samples; i++) {
@@ -203,7 +203,7 @@ static int _synth(int frequency, int duration, float amplitude,
return i; return i;
} }
static void _taper(short *sample_buf, int samples) { static void _taper(short* sample_buf, int samples) {
int i; int i;
const float TAPER_SAMPLES_FRACTION = 0.1f; const float TAPER_SAMPLES_FRACTION = 0.1f;
int taper_samples = (int)(TAPER_SAMPLES_FRACTION * samples); int taper_samples = (int)(TAPER_SAMPLES_FRACTION * samples);
@@ -218,7 +218,7 @@ static void _taper(short *sample_buf, int samples) {
} }
} }
void SfxMan::PlayTone(const char *tone) { void SfxMan::PlayTone(const char* tone) {
if (!mInitOk) { if (!mInitOk) {
LOGW("SfxMan: not playing sound because initialization failed."); LOGW("SfxMan: not playing sound because initialization failed.");
return; return;

View File

@@ -138,7 +138,7 @@ void Shader::BindShader() {
void Shader::UnbindShader() { glUseProgram(0); } void Shader::UnbindShader() { glUseProgram(0); }
// To be called by child classes only. // To be called by child classes only.
void Shader::PushMVPMatrix(glm::mat4 *mat) { void Shader::PushMVPMatrix(glm::mat4* mat) {
MY_ASSERT(mMVPMatrixLoc >= 0); MY_ASSERT(mMVPMatrixLoc >= 0);
glUniformMatrix4fv(mMVPMatrixLoc, 1, GL_FALSE, glm::value_ptr(*mat)); glUniformMatrix4fv(mMVPMatrixLoc, 1, GL_FALSE, glm::value_ptr(*mat));
} }
@@ -151,7 +151,7 @@ void Shader::PushPositions(int vbo_offset, int stride) {
glEnableVertexAttribArray(mPositionAttribLoc); glEnableVertexAttribArray(mPositionAttribLoc);
} }
void Shader::BeginRender(VertexBuf *vbuf) { void Shader::BeginRender(VertexBuf* vbuf) {
// Activate shader // Activate shader
BindShader(); BindShader();
@@ -165,7 +165,7 @@ void Shader::BeginRender(VertexBuf *vbuf) {
mPreparedVertexBuf = vbuf; mPreparedVertexBuf = vbuf;
} }
void Shader::Render(IndexBuf *ibuf, glm::mat4 *mvpMat) { void Shader::Render(IndexBuf* ibuf, glm::mat4* mvpMat) {
MY_ASSERT(mPreparedVertexBuf != NULL); MY_ASSERT(mPreparedVertexBuf != NULL);
// push MVP matrix to shader // push MVP matrix to shader
@@ -215,7 +215,7 @@ void TrivialShader::Compile() {
UnbindShader(); UnbindShader();
} }
const char *TrivialShader::GetVertShaderSource() { const char* TrivialShader::GetVertShaderSource() {
return "uniform mat4 u_MVP; \n" return "uniform mat4 u_MVP; \n"
"uniform vec4 u_Tint; \n" "uniform vec4 u_Tint; \n"
"attribute vec4 a_Position; \n" "attribute vec4 a_Position; \n"
@@ -229,7 +229,7 @@ const char *TrivialShader::GetVertShaderSource() {
"} \n"; "} \n";
} }
const char *TrivialShader::GetFragShaderSource() { const char* TrivialShader::GetFragShaderSource() {
return "precision mediump float; \n" return "precision mediump float; \n"
"varying vec4 v_Color; \n" "varying vec4 v_Color; \n"
"void main() \n" "void main() \n"
@@ -240,7 +240,7 @@ const char *TrivialShader::GetFragShaderSource() {
int TrivialShader::GetColorAttribLoc() { return mColorLoc; } int TrivialShader::GetColorAttribLoc() { return mColorLoc; }
const char *TrivialShader::GetShaderName() { return "TrivialShader"; } const char* TrivialShader::GetShaderName() { return "TrivialShader"; }
void TrivialShader::ResetTintColor() { SetTintColor(1.0f, 1.0f, 1.0f); } void TrivialShader::ResetTintColor() { SetTintColor(1.0f, 1.0f, 1.0f); }
@@ -256,7 +256,7 @@ void TrivialShader::SetTintColor(float r, float g, float b) {
} }
} }
void TrivialShader::BeginRender(VertexBuf *geom) { void TrivialShader::BeginRender(VertexBuf* geom) {
// let superclass do the basic work // let superclass do the basic work
Shader::BeginRender(geom); Shader::BeginRender(geom);

View File

@@ -29,16 +29,16 @@ static GLfloat RECT_VERTICES[] = {
// indices // indices
static GLushort RECT_INDICES[] = {0, 1, 2, 0, 2, 3}; static GLushort RECT_INDICES[] = {0, 1, 2, 0, 2, 3};
ShapeRenderer::ShapeRenderer(TrivialShader *ts) { ShapeRenderer::ShapeRenderer(TrivialShader* ts) {
mTrivialShader = ts; mTrivialShader = ts;
mColor[0] = mColor[1] = mColor[2] = 1.0f; mColor[0] = mColor[1] = mColor[2] = 1.0f;
mGeom = NULL; mGeom = NULL;
// create geometry // create geometry
VertexBuf *vbuf = VertexBuf* vbuf =
new VertexBuf(RECT_VERTICES, sizeof(RECT_VERTICES), 7 * sizeof(GLfloat)); new VertexBuf(RECT_VERTICES, sizeof(RECT_VERTICES), 7 * sizeof(GLfloat));
vbuf->SetColorsOffset(3 * sizeof(GLfloat)); vbuf->SetColorsOffset(3 * sizeof(GLfloat));
IndexBuf *ibuf = new IndexBuf(RECT_INDICES, sizeof(RECT_INDICES)); IndexBuf* ibuf = new IndexBuf(RECT_INDICES, sizeof(RECT_INDICES));
mGeom = new SimpleGeom(vbuf, ibuf); mGeom = new SimpleGeom(vbuf, ibuf);
} }

View File

@@ -15,7 +15,7 @@
*/ */
#include "tex_quad.hpp" #include "tex_quad.hpp"
static void _put_vertex(float *v, float x, float y, float tex_u, float tex_v) { static void _put_vertex(float* v, float x, float y, float tex_u, float tex_v) {
// position // position
v[0] = x; v[0] = x;
v[1] = y; v[1] = y;
@@ -37,9 +37,9 @@ void TexQuad::CreateGeom(float umin, float vmin, float umax, float vmax) {
9; // 3 for coords, 4 for color, 2 for tex coordinates 9; // 3 for coords, 4 for color, 2 for tex coordinates
const int stride_bytes = stride_floats * sizeof(GLfloat); const int stride_bytes = stride_floats * sizeof(GLfloat);
int vertices = stride_floats * 4; // 4 vertices int vertices = stride_floats * 4; // 4 vertices
GLfloat *geom = new GLfloat[vertices]; GLfloat* geom = new GLfloat[vertices];
int geom_size = sizeof(GLfloat) * vertices; int geom_size = sizeof(GLfloat) * vertices;
GLushort *indices = new GLushort[6]; // 6 indices GLushort* indices = new GLushort[6]; // 6 indices
int indices_size = sizeof(GLushort) * 6; int indices_size = sizeof(GLushort) * 6;
float left = -mAspect * 0.5f; float left = -mAspect * 0.5f;
float right = mAspect * 0.5f; float right = mAspect * 0.5f;
@@ -66,10 +66,10 @@ void TexQuad::CreateGeom(float umin, float vmin, float umax, float vmax) {
indices[5] = 3; indices[5] = 3;
// prepare geometry // prepare geometry
VertexBuf *vbuf = new VertexBuf(geom, geom_size, stride_bytes); VertexBuf* vbuf = new VertexBuf(geom, geom_size, stride_bytes);
vbuf->SetColorsOffset(3 * sizeof(GLfloat)); vbuf->SetColorsOffset(3 * sizeof(GLfloat));
vbuf->SetTexCoordsOffset(7 * sizeof(GLfloat)); vbuf->SetTexCoordsOffset(7 * sizeof(GLfloat));
IndexBuf *ibuf = new IndexBuf(indices, indices_size); IndexBuf* ibuf = new IndexBuf(indices, indices_size);
mGeom = new SimpleGeom(vbuf, ibuf); mGeom = new SimpleGeom(vbuf, ibuf);
// clean up our temporary buffers // clean up our temporary buffers
@@ -79,7 +79,7 @@ void TexQuad::CreateGeom(float umin, float vmin, float umax, float vmax) {
indices = NULL; indices = NULL;
} }
void TexQuad::Render(glm::mat4 *transform) { void TexQuad::Render(glm::mat4* transform) {
float aspect = SceneManager::GetInstance()->GetScreenAspect(); float aspect = SceneManager::GetInstance()->GetScreenAspect();
glm::mat4 orthoMat = glm::ortho(0.0f, aspect, 0.0f, 1.0f); glm::mat4 orthoMat = glm::ortho(0.0f, aspect, 0.0f, 1.0f);
glm::mat4 modelMat, mat; glm::mat4 modelMat, mat;

View File

@@ -26,7 +26,7 @@
#define CORRECTION_Y -0.02f #define CORRECTION_Y -0.02f
TextRenderer::TextRenderer(TrivialShader *t) { TextRenderer::TextRenderer(TrivialShader* t) {
mTrivialShader = t; mTrivialShader = t;
memset(mCharGeom, 0, sizeof(mCharGeom)); memset(mCharGeom, 0, sizeof(mCharGeom));
mFontScale = 1.0f; mFontScale = 1.0f;
@@ -50,12 +50,12 @@ TextRenderer::~TextRenderer() {
} }
} }
TextRenderer *TextRenderer::SetFontScale(float scale) { TextRenderer* TextRenderer::SetFontScale(float scale) {
mFontScale = scale; mFontScale = scale;
return this; return this;
} }
static void _count_rows_cols(const char *p, int *outCols, int *outRows) { static void _count_rows_cols(const char* p, int* outCols, int* outRows) {
int textCols = 0, textRows = 1; int textCols = 0, textRows = 1;
int curCols = 0; int curCols = 0;
for (; *p; ++p) { for (; *p; ++p) {
@@ -73,14 +73,14 @@ static void _count_rows_cols(const char *p, int *outCols, int *outRows) {
*outRows = textRows; *outRows = textRows;
} }
TextRenderer *TextRenderer::SetMatrix(glm::mat4 m) { TextRenderer* TextRenderer::SetMatrix(glm::mat4 m) {
mMatrix = m; mMatrix = m;
return this; return this;
} }
void TextRenderer::MeasureText(const char *str, float fontScale, void TextRenderer::MeasureText(const char* str, float fontScale,
float *outWidth, float* outWidth,
float *outHeight) { // static! float* outHeight) { // static!
int rows, cols; int rows, cols;
_count_rows_cols(str, &cols, &rows); _count_rows_cols(str, &cols, &rows);
if (outWidth) { if (outWidth) {
@@ -91,7 +91,7 @@ void TextRenderer::MeasureText(const char *str, float fontScale,
} }
} }
TextRenderer *TextRenderer::RenderText(const char *str, float centerX, TextRenderer* TextRenderer::RenderText(const char* str, float centerX,
float centerY) { float centerY) {
float aspect = SceneManager::GetInstance()->GetScreenAspect(); float aspect = SceneManager::GetInstance()->GetScreenAspect();
glm::mat4 orthoMat = glm::ortho(0.0f, aspect, 0.0f, 1.0f); glm::mat4 orthoMat = glm::ortho(0.0f, aspect, 0.0f, 1.0f);

View File

@@ -18,7 +18,7 @@
#include "common.hpp" #include "common.hpp"
void Texture::InitFromRawRGB(int width, int height, bool hasAlpha, void Texture::InitFromRawRGB(int width, int height, bool hasAlpha,
const unsigned char *data) { const unsigned char* data) {
GLenum format = hasAlpha ? GL_RGBA : GL_RGB; GLenum format = hasAlpha ? GL_RGBA : GL_RGB;
glGenTextures(1, &mTextureH); glGenTextures(1, &mTextureH);

View File

@@ -57,9 +57,9 @@ UiScene::~UiScene() {
mWidgetCount = 0; mWidgetCount = 0;
} }
UiWidget *UiScene::NewWidget() { UiWidget* UiScene::NewWidget() {
MY_ASSERT(mWidgetCount + 1 < MAX_WIDGETS); MY_ASSERT(mWidgetCount + 1 < MAX_WIDGETS);
UiWidget *widget = new UiWidget(mWidgetCount); UiWidget* widget = new UiWidget(mWidgetCount);
mWidgets[mWidgetCount++] = widget; mWidgets[mWidgetCount++] = widget;
return widget; return widget;
} }
@@ -97,19 +97,19 @@ void UiScene::OnKillGraphics() {
void UiScene::OnScreenResized(int width, int height) { void UiScene::OnScreenResized(int width, int height) {
// screen got resized; if we have widgets and graphics, we have to recreate // screen got resized; if we have widgets and graphics, we have to recreate
// them // them
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
if (mgr->HasGraphics() && mWidgetCount > 0) { if (mgr->HasGraphics() && mWidgetCount > 0) {
DeleteWidgets(); DeleteWidgets();
OnCreateWidgets(); OnCreateWidgets();
} }
} }
UiWidget *UiScene::GetWidgetById(int id) { UiWidget* UiScene::GetWidgetById(int id) {
return (id < 0 || id >= mWidgetCount) ? NULL : mWidgets[id]; return (id < 0 || id >= mWidgetCount) ? NULL : mWidgets[id];
} }
void UiScene::DoFrame() { void UiScene::DoFrame() {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
// clear screen // clear screen
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
@@ -162,7 +162,7 @@ void UiScene::OnButtonClicked(int buttonId) {
// base classes override this to react to button clicks // base classes override this to react to button clicks
} }
void UiScene::UpdateTouchFocus(const struct PointerCoords *coords) { void UiScene::UpdateTouchFocus(const struct PointerCoords* coords) {
// translate to our coordinate system // translate to our coordinate system
float h = SceneManager::GetInstance()->GetScreenHeight(); float h = SceneManager::GetInstance()->GetScreenHeight();
float x = coords->x / h; float x = coords->x / h;
@@ -171,7 +171,7 @@ void UiScene::UpdateTouchFocus(const struct PointerCoords *coords) {
int i; int i;
mFocusWidget = -1; mFocusWidget = -1;
for (i = 0; i < mWidgetCount; ++i) { for (i = 0; i < mWidgetCount; ++i) {
UiWidget *w = mWidgets[i]; UiWidget* w = mWidgets[i];
if (w->PointBelongs(x, y) && w->IsClickableButton()) { if (w->PointBelongs(x, y) && w->IsClickableButton()) {
mFocusWidget = i; mFocusWidget = i;
return; return;
@@ -179,7 +179,7 @@ void UiScene::UpdateTouchFocus(const struct PointerCoords *coords) {
} }
} }
void UiScene::OnPointerDown(int pointerId, const struct PointerCoords *coords) { void UiScene::OnPointerDown(int pointerId, const struct PointerCoords* coords) {
// If this event was generated by something that's not associated to the // If this event was generated by something that's not associated to the
// screen, (like a trackpad), ignore it, because our UI is not driven that // screen, (like a trackpad), ignore it, because our UI is not driven that
// way. // way.
@@ -189,13 +189,13 @@ void UiScene::OnPointerDown(int pointerId, const struct PointerCoords *coords) {
} }
} }
void UiScene::OnPointerMove(int pointerId, const struct PointerCoords *coords) { void UiScene::OnPointerMove(int pointerId, const struct PointerCoords* coords) {
if (coords->isScreen && mPointerDown && !mWaitScreen) { if (coords->isScreen && mPointerDown && !mWaitScreen) {
UpdateTouchFocus(coords); UpdateTouchFocus(coords);
} }
} }
void UiScene::OnPointerUp(int pointerId, const struct PointerCoords *coords) { void UiScene::OnPointerUp(int pointerId, const struct PointerCoords* coords) {
if (!coords->isScreen || mWaitScreen) { if (!coords->isScreen || mWaitScreen) {
return; return;
} }
@@ -216,7 +216,7 @@ void UiScene::OnPointerUp(int pointerId, const struct PointerCoords *coords) {
} }
void UiScene::DispatchButtonClick(int id) { void UiScene::DispatchButtonClick(int id) {
UiWidget *w = GetWidgetById(id); UiWidget* w = GetWidgetById(id);
if (w && w->IsClickableButton()) { if (w && w->IsClickableButton()) {
OnButtonClicked(id); OnButtonClicked(id);
} }
@@ -228,7 +228,7 @@ int UiScene::FindDefaultButton() {
} }
int i; int i;
for (i = 0; i < mWidgetCount; ++i) { for (i = 0; i < mWidgetCount; ++i) {
UiWidget *w = mWidgets[i]; UiWidget* w = mWidgets[i];
if (w->IsClickableButton()) { if (w->IsClickableButton()) {
return i; return i;
} }
@@ -267,8 +267,8 @@ void UiScene::OnKeyDown(int ourKeyCode) {
} else { } else {
// navigate // navigate
int destId = -1; int destId = -1;
UiWidget *w = GetWidgetById(mFocusWidget); UiWidget* w = GetWidgetById(mFocusWidget);
UiWidget *destWidget = UiWidget* destWidget =
w ? GetWidgetById(destId = w->GetNav(navDir)) : NULL; w ? GetWidgetById(destId = w->GetNav(navDir)) : NULL;
if (destWidget && destWidget->IsClickableButton()) { if (destWidget && destWidget->IsClickableButton()) {
// navigate to that widget // navigate to that widget
@@ -279,15 +279,15 @@ void UiScene::OnKeyDown(int ourKeyCode) {
} }
void UiScene::AddNav(int fromWidgetId, int dir, int toWidgetId) { void UiScene::AddNav(int fromWidgetId, int dir, int toWidgetId) {
UiWidget *from = GetWidgetById(fromWidgetId); UiWidget* from = GetWidgetById(fromWidgetId);
UiWidget *to = GetWidgetById(toWidgetId); UiWidget* to = GetWidgetById(toWidgetId);
if (from && to) { if (from && to) {
from->SetNav(dir, toWidgetId); from->SetNav(dir, toWidgetId);
} }
} }
static void _apply_transition(int trans, float f, float *x, float *y, float *w, static void _apply_transition(int trans, float f, float* x, float* y, float* w,
float *h, float *fontScale) { float* h, float* fontScale) {
float maxX = SceneManager::GetInstance()->GetScreenAspect(); float maxX = SceneManager::GetInstance()->GetScreenAspect();
switch (trans) { switch (trans) {
case UiWidget::TRANS_SCALE: case UiWidget::TRANS_SCALE:
@@ -310,8 +310,8 @@ static void _apply_transition(int trans, float f, float *x, float *y, float *w,
} }
} }
void UiWidget::Render(TrivialShader *trivialShader, TextRenderer *textRenderer, void UiWidget::Render(TrivialShader* trivialShader, TextRenderer* textRenderer,
ShapeRenderer *shapeRenderer, int focus, ShapeRenderer* shapeRenderer, int focus,
float transitionFactor) { float transitionFactor) {
if (!mVisible) { if (!mVisible) {
// that was easy. // that was easy.
@@ -322,7 +322,7 @@ void UiWidget::Render(TrivialShader *trivialShader, TextRenderer *textRenderer,
float factor = pulse ? SineWave(1.0f - PULSE_AMOUNT, 1.0f + PULSE_AMOUNT, float factor = pulse ? SineWave(1.0f - PULSE_AMOUNT, 1.0f + PULSE_AMOUNT,
PULSE_PERIOD, 0.0f) PULSE_PERIOD, 0.0f)
: 1.0f; : 1.0f;
const float *color = (mIsButton && focus == FOCUS_YES) ? BUTTON_FOCUS_COLOR const float* color = (mIsButton && focus == FOCUS_YES) ? BUTTON_FOCUS_COLOR
: (mIsButton && !mEnabled) ? BUTTON_DISABLED_COLOR : (mIsButton && !mEnabled) ? BUTTON_DISABLED_COLOR
: mTextColor; : mTextColor;
float borderSize = 0.0f; float borderSize = 0.0f;

View File

@@ -15,7 +15,7 @@
*/ */
#include "vertexbuf.hpp" #include "vertexbuf.hpp"
VertexBuf::VertexBuf(GLfloat *geomData, int dataSize, int stride) { VertexBuf::VertexBuf(GLfloat* geomData, int dataSize, int stride) {
MY_ASSERT(dataSize % stride == 0); MY_ASSERT(dataSize % stride == 0);
mPrimitive = GL_TRIANGLES; mPrimitive = GL_TRIANGLES;

View File

@@ -53,7 +53,7 @@ void WelcomeScene::RenderBackground() {
} }
void WelcomeScene::OnButtonClicked(int id) { void WelcomeScene::OnButtonClicked(int id) {
SceneManager *mgr = SceneManager::GetInstance(); SceneManager* mgr = SceneManager::GetInstance();
if (id == mPlayButtonId) { if (id == mPlayButtonId) {
mgr->RequestNewScene(new PlayScene()); mgr->RequestNewScene(new PlayScene());

View File

@@ -22,7 +22,7 @@
#include <string.h> #include <string.h>
// Android log function wrappers // Android log function wrappers
static const char *kTAG = "hello-jniCallback"; static const char* kTAG = "hello-jniCallback";
#define LOGI(...) \ #define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_INFO, kTAG, __VA_ARGS__)) ((void)__android_log_print(ANDROID_LOG_INFO, kTAG, __VA_ARGS__))
#define LOGW(...) \ #define LOGW(...) \
@@ -32,7 +32,7 @@ static const char *kTAG = "hello-jniCallback";
// processing callback to handler class // processing callback to handler class
typedef struct tick_context { typedef struct tick_context {
JavaVM *javaVM; JavaVM* javaVM;
jclass jniHandlerClz; jclass jniHandlerClz;
jobject jniHandlerObj; jobject jniHandlerObj;
jclass mainActivityClz; jclass mainActivityClz;
@@ -49,7 +49,7 @@ TickContext g_ctx;
* hello-jniCallback/app/src/main/java/com/example/hellojnicallback/MainActivity.java * hello-jniCallback/app/src/main/java/com/example/hellojnicallback/MainActivity.java
*/ */
JNIEXPORT jstring JNICALL JNIEXPORT jstring JNICALL
Java_com_example_hellojnicallback_MainActivity_stringFromJNI(JNIEnv *env, Java_com_example_hellojnicallback_MainActivity_stringFromJNI(JNIEnv* env,
jobject thiz) { jobject thiz) {
#if defined(__arm__) #if defined(__arm__)
#if defined(__ARM_ARCH_7A__) #if defined(__ARM_ARCH_7A__)
@@ -93,7 +93,7 @@ Java_com_example_hellojnicallback_MainActivity_stringFromJNI(JNIEnv *env,
* The trivial implementation for these functions are inside file * The trivial implementation for these functions are inside file
* JniHandler.java * JniHandler.java
*/ */
void queryRuntimeInfo(JNIEnv *env, jobject instance) { void queryRuntimeInfo(JNIEnv* env, jobject instance) {
// Find out which OS we are running on. It does not matter for this app // Find out which OS we are running on. It does not matter for this app
// just to demo how to call static functions. // just to demo how to call static functions.
// Our java JniHandler class id and instance are initialized when this // Our java JniHandler class id and instance are initialized when this
@@ -108,7 +108,7 @@ void queryRuntimeInfo(JNIEnv *env, jobject instance) {
} }
jstring buildVersion = jstring buildVersion =
(*env)->CallStaticObjectMethod(env, g_ctx.jniHandlerClz, versionFunc); (*env)->CallStaticObjectMethod(env, g_ctx.jniHandlerClz, versionFunc);
const char *version = (*env)->GetStringUTFChars(env, buildVersion, NULL); const char* version = (*env)->GetStringUTFChars(env, buildVersion, NULL);
if (!version) { if (!version) {
LOGE("Unable to get version string @ line %d", __LINE__); LOGE("Unable to get version string @ line %d", __LINE__);
return; return;
@@ -144,12 +144,12 @@ void queryRuntimeInfo(JNIEnv *env, jobject instance) {
* we rely on system to free all global refs when it goes away; * we rely on system to free all global refs when it goes away;
* the pairing function JNI_OnUnload() never gets called at all. * the pairing function JNI_OnUnload() never gets called at all.
*/ */
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv *env; JNIEnv* env;
memset(&g_ctx, 0, sizeof(g_ctx)); memset(&g_ctx, 0, sizeof(g_ctx));
g_ctx.javaVM = vm; g_ctx.javaVM = vm;
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) { if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR; // JNI version not supported. return JNI_ERR; // JNI version not supported.
} }
@@ -173,8 +173,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
* JNI allow us to call this function via an instance even it is * JNI allow us to call this function via an instance even it is
* private function. * private function.
*/ */
void sendJavaMsg(JNIEnv *env, jobject instance, jmethodID func, void sendJavaMsg(JNIEnv* env, jobject instance, jmethodID func,
const char *msg) { const char* msg) {
jstring javaMsg = (*env)->NewStringUTF(env, msg); jstring javaMsg = (*env)->NewStringUTF(env, msg);
(*env)->CallVoidMethod(env, instance, func, javaMsg); (*env)->CallVoidMethod(env, instance, func, javaMsg);
(*env)->DeleteLocalRef(env, javaMsg); (*env)->DeleteLocalRef(env, javaMsg);
@@ -185,11 +185,11 @@ void sendJavaMsg(JNIEnv *env, jobject instance, jmethodID func,
* calling back to MainActivity::updateTimer() to display ticks on UI * calling back to MainActivity::updateTimer() to display ticks on UI
* calling back to JniHandler::updateStatus(String msg) for msg * calling back to JniHandler::updateStatus(String msg) for msg
*/ */
void *UpdateTicks(void *context) { void* UpdateTicks(void* context) {
TickContext *pctx = (TickContext *)context; TickContext* pctx = (TickContext*)context;
JavaVM *javaVM = pctx->javaVM; JavaVM* javaVM = pctx->javaVM;
JNIEnv *env; JNIEnv* env;
jint res = (*javaVM)->GetEnv(javaVM, (void **)&env, JNI_VERSION_1_6); jint res = (*javaVM)->GetEnv(javaVM, (void**)&env, JNI_VERSION_1_6);
if (res != JNI_OK) { if (res != JNI_OK) {
res = (*javaVM)->AttachCurrentThread(javaVM, &env, NULL); res = (*javaVM)->AttachCurrentThread(javaVM, &env, NULL);
if (JNI_OK != res) { if (JNI_OK != res) {
@@ -251,7 +251,7 @@ void *UpdateTicks(void *context) {
* Interface to Java side to start ticks, caller is from onResume() * Interface to Java side to start ticks, caller is from onResume()
*/ */
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_example_hellojnicallback_MainActivity_startTicks(JNIEnv *env, Java_com_example_hellojnicallback_MainActivity_startTicks(JNIEnv* env,
jobject instance) { jobject instance) {
pthread_t threadInfo_; pthread_t threadInfo_;
pthread_attr_t threadAttr_; pthread_attr_t threadAttr_;
@@ -279,7 +279,7 @@ Java_com_example_hellojnicallback_MainActivity_startTicks(JNIEnv *env,
* for a clean shutdown. The caller is from onPause * for a clean shutdown. The caller is from onPause
*/ */
JNIEXPORT void JNICALL Java_com_example_hellojnicallback_MainActivity_StopTicks( JNIEXPORT void JNICALL Java_com_example_hellojnicallback_MainActivity_StopTicks(
JNIEnv *env, jobject instance) { JNIEnv* env, jobject instance) {
pthread_mutex_lock(&g_ctx.lock); pthread_mutex_lock(&g_ctx.lock);
g_ctx.done = 1; g_ctx.done = 1;
pthread_mutex_unlock(&g_ctx.lock); pthread_mutex_unlock(&g_ctx.lock);

View File

@@ -32,7 +32,7 @@
* app/src/main/java/com/example/hellolibs/MainActivity.java * app/src/main/java/com/example/hellolibs/MainActivity.java
*/ */
extern "C" JNIEXPORT jlong JNICALL extern "C" JNIEXPORT jlong JNICALL
Java_com_example_hellolibs_MainActivity_measureTicks(JNIEnv *env, Java_com_example_hellolibs_MainActivity_measureTicks(JNIEnv* env,
jobject thiz) { jobject thiz) {
auto ticks = GetTicks(); auto ticks = GetTicks();

View File

@@ -50,10 +50,10 @@ class OboeSinePlayer : public oboe::AudioStreamCallback {
// This class will also be used for the callback // This class will also be used for the callback
// For more complicated callbacks create a separate class // For more complicated callbacks create a separate class
oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboeStream, oboe::DataCallbackResult onAudioReady(oboe::AudioStream* oboeStream,
void *audioData, void* audioData,
int32_t numFrames) override { int32_t numFrames) override {
float *floatData = static_cast<float *>(audioData); float* floatData = static_cast<float*>(audioData);
if (isOn) { if (isOn) {
// Generate sine wave values // Generate sine wave values
for (int i = 0; i < numFrames; ++i) { for (int i = 0; i < numFrames; ++i) {

View File

@@ -19,7 +19,7 @@
#include "OboeSinePlayer.h" #include "OboeSinePlayer.h"
static OboeSinePlayer *oboePlayer = nullptr; static OboeSinePlayer* oboePlayer = nullptr;
extern "C" { extern "C" {
/* Create Oboe playback stream /* Create Oboe playback stream
@@ -28,14 +28,14 @@ extern "C" {
*/ */
JNIEXPORT jint JNICALL JNIEXPORT jint JNICALL
Java_com_google_example_hellooboe_MainActivity_createStream( Java_com_google_example_hellooboe_MainActivity_createStream(
JNIEnv * /* env */, jobject /* this */) { JNIEnv* /* env */, jobject /* this */) {
oboePlayer = new OboeSinePlayer(); oboePlayer = new OboeSinePlayer();
return oboePlayer ? 0 : -1; return oboePlayer ? 0 : -1;
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_google_example_hellooboe_MainActivity_destroyStream( Java_com_google_example_hellooboe_MainActivity_destroyStream(
JNIEnv * /* env */, jobject /* this */) { JNIEnv* /* env */, jobject /* this */) {
if (oboePlayer) { if (oboePlayer) {
delete oboePlayer; delete oboePlayer;
oboePlayer = nullptr; oboePlayer = nullptr;
@@ -47,7 +47,7 @@ Java_com_google_example_hellooboe_MainActivity_destroyStream(
* -1 - failed (stream has not created yet ) * -1 - failed (stream has not created yet )
*/ */
JNIEXPORT jint JNICALL Java_com_google_example_hellooboe_MainActivity_playSound( JNIEXPORT jint JNICALL Java_com_google_example_hellooboe_MainActivity_playSound(
JNIEnv * /* env */, jobject /* this */, jboolean enable) { JNIEnv* /* env */, jobject /* this */, jboolean enable) {
jint result = 0; jint result = 0;
if (oboePlayer) { if (oboePlayer) {
oboePlayer->enable(enable); oboePlayer->enable(enable);

View File

@@ -72,14 +72,14 @@ struct SwapChainSupportDetails {
}; };
struct ANativeWindowDeleter { struct ANativeWindowDeleter {
void operator()(ANativeWindow *window) { ANativeWindow_release(window); } void operator()(ANativeWindow* window) { ANativeWindow_release(window); }
}; };
std::vector<uint8_t> LoadBinaryFileToVector(const char *file_path, std::vector<uint8_t> LoadBinaryFileToVector(const char* file_path,
AAssetManager *assetManager) { AAssetManager* assetManager) {
std::vector<uint8_t> file_content; std::vector<uint8_t> file_content;
assert(assetManager); assert(assetManager);
AAsset *file = AAsset* file =
AAssetManager_open(assetManager, file_path, AASSET_MODE_BUFFER); AAssetManager_open(assetManager, file_path, AASSET_MODE_BUFFER);
size_t file_length = AAsset_getLength(file); size_t file_length = AAsset_getLength(file);
@@ -90,7 +90,7 @@ std::vector<uint8_t> LoadBinaryFileToVector(const char *file_path,
return file_content; return file_content;
} }
const char *toStringMessageSeverity(VkDebugUtilsMessageSeverityFlagBitsEXT s) { const char* toStringMessageSeverity(VkDebugUtilsMessageSeverityFlagBitsEXT s) {
switch (s) { switch (s) {
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
return "VERBOSE"; return "VERBOSE";
@@ -104,7 +104,7 @@ const char *toStringMessageSeverity(VkDebugUtilsMessageSeverityFlagBitsEXT s) {
return "UNKNOWN"; return "UNKNOWN";
} }
} }
const char *toStringMessageType(VkDebugUtilsMessageTypeFlagsEXT s) { const char* toStringMessageType(VkDebugUtilsMessageTypeFlagsEXT s) {
if (s == (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | if (s == (VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT)) VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT))
@@ -128,8 +128,8 @@ const char *toStringMessageType(VkDebugUtilsMessageTypeFlagsEXT s) {
static VKAPI_ATTR VkBool32 VKAPI_CALL static VKAPI_ATTR VkBool32 VKAPI_CALL
debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType, VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void * /* pUserData */) { void* /* pUserData */) {
auto ms = toStringMessageSeverity(messageSeverity); auto ms = toStringMessageSeverity(messageSeverity);
auto mt = toStringMessageType(messageType); auto mt = toStringMessageType(messageType);
printf("[%s: %s]\n%s\n", ms, mt, pCallbackData->pMessage); printf("[%s: %s]\n%s\n", ms, mt, pCallbackData->pMessage);
@@ -138,7 +138,7 @@ debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
} }
static void populateDebugMessengerCreateInfo( static void populateDebugMessengerCreateInfo(
VkDebugUtilsMessengerCreateInfoEXT &createInfo) { VkDebugUtilsMessengerCreateInfoEXT& createInfo) {
createInfo = {}; createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
@@ -151,9 +151,9 @@ static void populateDebugMessengerCreateInfo(
} }
static VkResult CreateDebugUtilsMessengerEXT( static VkResult CreateDebugUtilsMessengerEXT(
VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks *pAllocator, const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT *pDebugMessenger) { VkDebugUtilsMessengerEXT* pDebugMessenger) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
instance, "vkCreateDebugUtilsMessengerEXT"); instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) { if (func != nullptr) {
@@ -165,7 +165,7 @@ static VkResult CreateDebugUtilsMessengerEXT(
static void DestroyDebugUtilsMessengerEXT( static void DestroyDebugUtilsMessengerEXT(
VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger,
const VkAllocationCallbacks *pAllocator) { const VkAllocationCallbacks* pAllocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr( auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
instance, "vkDestroyDebugUtilsMessengerEXT"); instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) { if (func != nullptr) {
@@ -179,7 +179,7 @@ class HelloVK {
void render(); void render();
void cleanup(); void cleanup();
void cleanupSwapChain(); void cleanupSwapChain();
void reset(ANativeWindow *newWindow, AAssetManager *newManager); void reset(ANativeWindow* newWindow, AAssetManager* newManager);
bool initialized = false; bool initialized = false;
private: private:
@@ -202,18 +202,18 @@ class HelloVK {
bool checkDeviceExtensionSupport(VkPhysicalDevice device); bool checkDeviceExtensionSupport(VkPhysicalDevice device);
bool isDeviceSuitable(VkPhysicalDevice device); bool isDeviceSuitable(VkPhysicalDevice device);
bool checkValidationLayerSupport(); bool checkValidationLayerSupport();
std::vector<const char *> getRequiredExtensions(bool enableValidation); std::vector<const char*> getRequiredExtensions(bool enableValidation);
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR &capabilities); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
VkShaderModule createShaderModule(const std::vector<uint8_t> &code); VkShaderModule createShaderModule(const std::vector<uint8_t>& code);
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex); void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex);
void recreateSwapChain(); void recreateSwapChain();
void onOrientationChange(); void onOrientationChange();
uint32_t findMemoryType(uint32_t typeFilter, uint32_t findMemoryType(uint32_t typeFilter,
VkMemoryPropertyFlags properties); VkMemoryPropertyFlags properties);
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage,
VkMemoryPropertyFlags properties, VkBuffer &buffer, VkMemoryPropertyFlags properties, VkBuffer& buffer,
VkDeviceMemory &bufferMemory); VkDeviceMemory& bufferMemory);
void createUniformBuffers(); void createUniformBuffers();
void updateUniformBuffer(uint32_t currentImage); void updateUniformBuffer(uint32_t currentImage);
void createDescriptorPool(); void createDescriptorPool();
@@ -230,12 +230,12 @@ class HelloVK {
*/ */
bool enableValidationLayers = false; bool enableValidationLayers = false;
const std::vector<const char *> validationLayers = { const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"}; "VK_LAYER_KHRONOS_validation"};
const std::vector<const char *> deviceExtensions = { const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME}; VK_KHR_SWAPCHAIN_EXTENSION_NAME};
std::unique_ptr<ANativeWindow, ANativeWindowDeleter> window; std::unique_ptr<ANativeWindow, ANativeWindowDeleter> window;
AAssetManager *assetManager; AAssetManager* assetManager;
VkInstance instance; VkInstance instance;
VkDebugUtilsMessengerEXT debugMessenger; VkDebugUtilsMessengerEXT debugMessenger;
@@ -306,8 +306,8 @@ void HelloVK::initVulkan() {
* satisfied by the device in use in order to be created. * satisfied by the device in use in order to be created.
*/ */
void HelloVK::createBuffer(VkDeviceSize size, VkBufferUsageFlags usage, void HelloVK::createBuffer(VkDeviceSize size, VkBufferUsageFlags usage,
VkMemoryPropertyFlags properties, VkBuffer &buffer, VkMemoryPropertyFlags properties, VkBuffer& buffer,
VkDeviceMemory &bufferMemory) { VkDeviceMemory& bufferMemory) {
VkBufferCreateInfo bufferInfo{}; VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size; bufferInfo.size = size;
@@ -382,7 +382,7 @@ void HelloVK::createDescriptorSetLayout() {
&descriptorSetLayout)); &descriptorSetLayout));
} }
void HelloVK::reset(ANativeWindow *newWindow, AAssetManager *newManager) { void HelloVK::reset(ANativeWindow* newWindow, AAssetManager* newManager) {
window.reset(newWindow); window.reset(newWindow);
assetManager = newManager; assetManager = newManager;
if (initialized) { if (initialized) {
@@ -468,9 +468,9 @@ void HelloVK::render() {
* getPrerotationMatrix handles screen rotation with 3 hardcoded rotation * getPrerotationMatrix handles screen rotation with 3 hardcoded rotation
* matrices (detailed below). We skip the 180 degrees rotation. * matrices (detailed below). We skip the 180 degrees rotation.
*/ */
void getPrerotationMatrix(const VkSurfaceCapabilitiesKHR &capabilities, void getPrerotationMatrix(const VkSurfaceCapabilitiesKHR& capabilities,
const VkSurfaceTransformFlagBitsKHR &pretransformFlag, const VkSurfaceTransformFlagBitsKHR& pretransformFlag,
std::array<float, 16> &mat) { std::array<float, 16>& mat) {
// mat is initialized to the identity matrix // mat is initialized to the identity matrix
mat = {1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.}; mat = {1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.};
if (pretransformFlag & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR) { if (pretransformFlag & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR) {
@@ -535,7 +535,7 @@ void HelloVK::updateUniformBuffer(uint32_t currentImage) {
UniformBufferObject ubo{}; UniformBufferObject ubo{};
getPrerotationMatrix(swapChainSupport.capabilities, pretransformFlag, getPrerotationMatrix(swapChainSupport.capabilities, pretransformFlag,
ubo.mvp); ubo.mvp);
void *data; void* data;
vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0, vkMapMemory(device, uniformBuffersMemory[currentImage], 0, sizeof(ubo), 0,
&data); &data);
memcpy(data, &ubo, sizeof(ubo)); memcpy(data, &ubo, sizeof(ubo));
@@ -657,9 +657,9 @@ bool HelloVK::checkValidationLayerSupport() {
std::vector<VkLayerProperties> availableLayers(layerCount); std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char *layerName : validationLayers) { for (const char* layerName : validationLayers) {
bool layerFound = false; bool layerFound = false;
for (const auto &layerProperties : availableLayers) { for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) { if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true; layerFound = true;
break; break;
@@ -673,9 +673,9 @@ bool HelloVK::checkValidationLayerSupport() {
return true; return true;
} }
std::vector<const char *> HelloVK::getRequiredExtensions( std::vector<const char*> HelloVK::getRequiredExtensions(
bool enableValidationLayers) { bool enableValidationLayers) {
std::vector<const char *> extensions; std::vector<const char*> extensions;
extensions.push_back("VK_KHR_surface"); extensions.push_back("VK_KHR_surface");
extensions.push_back("VK_KHR_android_surface"); extensions.push_back("VK_KHR_android_surface");
if (enableValidationLayers) { if (enableValidationLayers) {
@@ -711,7 +711,7 @@ void HelloVK::createInstance() {
static_cast<uint32_t>(validationLayers.size()); static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data(); createInfo.ppEnabledLayerNames = validationLayers.data();
populateDebugMessengerCreateInfo(debugCreateInfo); populateDebugMessengerCreateInfo(debugCreateInfo);
createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT *)&debugCreateInfo; createInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debugCreateInfo;
} else { } else {
createInfo.enabledLayerCount = 0; createInfo.enabledLayerCount = 0;
createInfo.pNext = nullptr; createInfo.pNext = nullptr;
@@ -724,7 +724,7 @@ void HelloVK::createInstance() {
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount,
extensions.data()); extensions.data());
LOGI("available extensions"); LOGI("available extensions");
for (const auto &extension : extensions) { for (const auto& extension : extensions) {
LOGI("\t %s", extension.extensionName); LOGI("\t %s", extension.extensionName);
} }
} }
@@ -763,7 +763,7 @@ QueueFamilyIndices HelloVK::findQueueFamilies(VkPhysicalDevice device) {
queueFamilies.data()); queueFamilies.data());
int i = 0; int i = 0;
for (const auto &queueFamily : queueFamilies) { for (const auto& queueFamily : queueFamilies) {
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
indices.graphicsFamily = i; indices.graphicsFamily = i;
} }
@@ -795,7 +795,7 @@ bool HelloVK::checkDeviceExtensionSupport(VkPhysicalDevice device) {
std::set<std::string> requiredExtensions(deviceExtensions.begin(), std::set<std::string> requiredExtensions(deviceExtensions.begin(),
deviceExtensions.end()); deviceExtensions.end());
for (const auto &extension : availableExtensions) { for (const auto& extension : availableExtensions) {
requiredExtensions.erase(extension.extensionName); requiredExtensions.erase(extension.extensionName);
} }
@@ -851,7 +851,7 @@ void HelloVK::pickPhysicalDevice() {
std::vector<VkPhysicalDevice> devices(deviceCount); std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data()); vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const auto &device : devices) { for (const auto& device : devices) {
if (isDeviceSuitable(device)) { if (isDeviceSuitable(device)) {
physicalDevice = device; physicalDevice = device;
break; break;
@@ -903,7 +903,7 @@ void HelloVK::createLogicalDeviceAndQueue() {
} }
VkExtent2D HelloVK::chooseSwapExtent( VkExtent2D HelloVK::chooseSwapExtent(
const VkSurfaceCapabilitiesKHR &capabilities) { const VkSurfaceCapabilitiesKHR& capabilities) {
if (capabilities.currentExtent.width != if (capabilities.currentExtent.width !=
std::numeric_limits<uint32_t>::max()) { std::numeric_limits<uint32_t>::max()) {
return capabilities.currentExtent; return capabilities.currentExtent;
@@ -945,8 +945,8 @@ void HelloVK::createSwapChain() {
querySwapChainSupport(physicalDevice); querySwapChainSupport(physicalDevice);
auto chooseSwapSurfaceFormat = auto chooseSwapSurfaceFormat =
[](const std::vector<VkSurfaceFormatKHR> &availableFormats) { [](const std::vector<VkSurfaceFormatKHR>& availableFormats) {
for (const auto &availableFormat : availableFormats) { for (const auto& availableFormat : availableFormats) {
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB &&
availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return availableFormat; return availableFormat;
@@ -1231,14 +1231,14 @@ void HelloVK::createGraphicsPipeline() {
vkDestroyShaderModule(device, vertShaderModule, nullptr); vkDestroyShaderModule(device, vertShaderModule, nullptr);
} }
VkShaderModule HelloVK::createShaderModule(const std::vector<uint8_t> &code) { VkShaderModule HelloVK::createShaderModule(const std::vector<uint8_t>& code) {
VkShaderModuleCreateInfo createInfo{}; VkShaderModuleCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = code.size(); createInfo.codeSize = code.size();
// Satisifies alignment requirements since the allocator // Satisifies alignment requirements since the allocator
// in vector ensures worst case requirements // in vector ensures worst case requirements
createInfo.pCode = reinterpret_cast<const uint32_t *>(code.data()); createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
VkShaderModule shaderModule; VkShaderModule shaderModule;
VK_CHECK(vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule)); VK_CHECK(vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule));

View File

@@ -40,8 +40,8 @@
* *
*/ */
struct VulkanEngine { struct VulkanEngine {
struct android_app *app; struct android_app* app;
vkt::HelloVK *app_backend; vkt::HelloVK* app_backend;
bool canRender = false; bool canRender = false;
}; };
@@ -49,8 +49,8 @@ struct VulkanEngine {
* Called by the Android runtime whenever events happen so the * Called by the Android runtime whenever events happen so the
* app can react to it. * app can react to it.
*/ */
static void HandleCmd(struct android_app *app, int32_t cmd) { static void HandleCmd(struct android_app* app, int32_t cmd) {
auto *engine = (VulkanEngine *)app->userData; auto* engine = (VulkanEngine*)app->userData;
switch (cmd) { switch (cmd) {
case APP_CMD_START: case APP_CMD_START:
if (engine->app->window != nullptr) { if (engine->app->window != nullptr) {
@@ -89,10 +89,10 @@ static void HandleCmd(struct android_app *app, int32_t cmd) {
* not use/process any input events, return false for all input events so system * not use/process any input events, return false for all input events so system
* can still process them. * can still process them.
*/ */
extern "C" bool VulkanKeyEventFilter(const GameActivityKeyEvent *event) { extern "C" bool VulkanKeyEventFilter(const GameActivityKeyEvent* event) {
return false; return false;
} }
extern "C" bool VulkanMotionEventFilter(const GameActivityMotionEvent *event) { extern "C" bool VulkanMotionEventFilter(const GameActivityMotionEvent* event) {
return false; return false;
} }
@@ -102,7 +102,7 @@ extern "C" bool VulkanMotionEventFilter(const GameActivityMotionEvent *event) {
* reported "handled" to OS. For details, refer to: * reported "handled" to OS. For details, refer to:
* d.android.com/games/agdk/game-activity/get-started#handle-events * d.android.com/games/agdk/game-activity/get-started#handle-events
*/ */
static void HandleInputEvents(struct android_app *app) { static void HandleInputEvents(struct android_app* app) {
auto inputBuf = android_app_swap_input_buffers(app); auto inputBuf = android_app_swap_input_buffers(app);
if (inputBuf == nullptr) { if (inputBuf == nullptr) {
return; return;
@@ -121,7 +121,7 @@ static void HandleInputEvents(struct android_app *app) {
* This can also be achieved more verbosely by manually declaring JNI functions * This can also be achieved more verbosely by manually declaring JNI functions
* and calling them from the Android application layer. * and calling them from the Android application layer.
*/ */
void android_main(struct android_app *state) { void android_main(struct android_app* state) {
VulkanEngine engine{}; VulkanEngine engine{};
vkt::HelloVK vulkanBackend{}; vkt::HelloVK vulkanBackend{};
@@ -134,9 +134,9 @@ void android_main(struct android_app *state) {
android_app_set_motion_event_filter(state, VulkanMotionEventFilter); android_app_set_motion_event_filter(state, VulkanMotionEventFilter);
while (!state->destroyRequested) { while (!state->destroyRequested) {
android_poll_source *source; android_poll_source* source;
auto result = ALooper_pollOnce(engine.canRender ? 0 : -1, nullptr, nullptr, auto result = ALooper_pollOnce(engine.canRender ? 0 : -1, nullptr, nullptr,
(void **)&source); (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");
std::abort(); std::abort();

View File

@@ -34,8 +34,9 @@
#define LOG_TAG "native-activity" #define LOG_TAG "native-activity"
#define _LOG(priority, fmt, ...) \ #define _LOG(priority, fmt, ...) \
((void)__android_log_print((priority), (LOG_TAG), (fmt)__VA_OPT__(, ) __VA_ARGS__)) ((void)__android_log_print((priority), (LOG_TAG), \
(fmt)__VA_OPT__(, ) __VA_ARGS__))
#define LOGE(fmt, ...) _LOG(ANDROID_LOG_ERROR, (fmt)__VA_OPT__(, ) __VA_ARGS__) #define LOGE(fmt, ...) _LOG(ANDROID_LOG_ERROR, (fmt)__VA_OPT__(, ) __VA_ARGS__)
#define LOGW(fmt, ...) _LOG(ANDROID_LOG_WARN, (fmt)__VA_OPT__(, ) __VA_ARGS__) #define LOGW(fmt, ...) _LOG(ANDROID_LOG_WARN, (fmt)__VA_OPT__(, ) __VA_ARGS__)
@@ -305,8 +306,7 @@ static void engine_term_display(Engine* engine) {
/** /**
* Process the next input event. * Process the next input event.
*/ */
static int32_t engine_handle_input(android_app* app, static int32_t engine_handle_input(android_app* app, AInputEvent* event) {
AInputEvent* event) {
auto* engine = (Engine*)app->userData; auto* engine = (Engine*)app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
engine->state.x = AMotionEvent_getX(event, 0); engine->state.x = AMotionEvent_getX(event, 0);
@@ -388,7 +388,7 @@ int OnSensorEvent(int /* fd */, int /* events */, void* data) {
* event loop for receiving input events and doing other things. * event loop for receiving input events and doing other things.
*/ */
void android_main(android_app* state) { void android_main(android_app* state) {
Engine engine {}; Engine engine{};
memset(&engine, 0, sizeof(engine)); memset(&engine, 0, sizeof(engine));
state->userData = &engine; state->userData = &engine;

View File

@@ -39,13 +39,13 @@ typedef struct loopermessage loopermessage;
struct loopermessage { struct loopermessage {
int what; int what;
void *obj; void* obj;
loopermessage *next; loopermessage* next;
bool quit; bool quit;
}; };
void *looper::trampoline(void *p) { void* looper::trampoline(void* p) {
((looper *)p)->loop(); ((looper*)p)->loop();
return NULL; return NULL;
} }
@@ -68,8 +68,8 @@ looper::~looper() {
} }
} }
void looper::post(int what, void *data, bool flush) { void looper::post(int what, void* data, bool flush) {
loopermessage *msg = new loopermessage(); loopermessage* msg = new loopermessage();
msg->what = what; msg->what = what;
msg->obj = data; msg->obj = data;
msg->next = NULL; msg->next = NULL;
@@ -77,13 +77,13 @@ void looper::post(int what, void *data, bool flush) {
addmsg(msg, flush); addmsg(msg, flush);
} }
void looper::addmsg(loopermessage *msg, bool flush) { void looper::addmsg(loopermessage* msg, bool flush) {
sem_wait(&headwriteprotect); sem_wait(&headwriteprotect);
loopermessage *h = head; loopermessage* h = head;
if (flush) { if (flush) {
while (h) { while (h) {
loopermessage *next = h->next; loopermessage* next = h->next;
delete h; delete h;
h = next; h = next;
} }
@@ -109,7 +109,7 @@ void looper::loop() {
// get next available message // get next available message
sem_wait(&headwriteprotect); sem_wait(&headwriteprotect);
loopermessage *msg = head; loopermessage* msg = head;
if (msg == NULL) { if (msg == NULL) {
LOGV("no msg"); LOGV("no msg");
sem_post(&headwriteprotect); sem_post(&headwriteprotect);
@@ -131,19 +131,19 @@ void looper::loop() {
void looper::quit() { void looper::quit() {
LOGV("quit"); LOGV("quit");
loopermessage *msg = new loopermessage(); loopermessage* msg = new loopermessage();
msg->what = 0; msg->what = 0;
msg->obj = NULL; msg->obj = NULL;
msg->next = NULL; msg->next = NULL;
msg->quit = true; msg->quit = true;
addmsg(msg, false); addmsg(msg, false);
void *retval; void* retval;
pthread_join(worker, &retval); pthread_join(worker, &retval);
sem_destroy(&headdataavailable); sem_destroy(&headdataavailable);
sem_destroy(&headwriteprotect); sem_destroy(&headwriteprotect);
running = false; running = false;
} }
void looper::handle(int what, void *obj) { void looper::handle(int what, void* obj) {
LOGV("dropping msg %d %p", what, obj); LOGV("dropping msg %d %p", what, obj);
} }

View File

@@ -52,9 +52,9 @@
typedef struct { typedef struct {
int fd; int fd;
ANativeWindow *window; ANativeWindow* window;
AMediaExtractor *ex; AMediaExtractor* ex;
AMediaCodec *codec; AMediaCodec* codec;
int64_t renderstart; int64_t renderstart;
bool sawInputEOS; bool sawInputEOS;
bool sawOutputEOS; bool sawOutputEOS;
@@ -74,10 +74,10 @@ enum {
}; };
class mylooper : public looper { class mylooper : public looper {
virtual void handle(int what, void *obj); virtual void handle(int what, void* obj);
}; };
static mylooper *mlooper = NULL; static mylooper* mlooper = NULL;
int64_t systemnanotime() { int64_t systemnanotime() {
timespec now; timespec now;
@@ -85,7 +85,7 @@ int64_t systemnanotime() {
return now.tv_sec * 1000000000LL + now.tv_nsec; return now.tv_sec * 1000000000LL + now.tv_nsec;
} }
void doCodecWork(workerdata *d) { void doCodecWork(workerdata* d) {
ssize_t bufidx = -1; ssize_t bufidx = -1;
if (!d->sawInputEOS) { if (!d->sawInputEOS) {
bufidx = AMediaCodec_dequeueInputBuffer(d->codec, 2000); bufidx = AMediaCodec_dequeueInputBuffer(d->codec, 2000);
@@ -147,14 +147,14 @@ void doCodecWork(workerdata *d) {
} }
} }
void mylooper::handle(int what, void *obj) { void mylooper::handle(int what, void* obj) {
switch (what) { switch (what) {
case kMsgCodecBuffer: case kMsgCodecBuffer:
doCodecWork((workerdata *)obj); doCodecWork((workerdata*)obj);
break; break;
case kMsgDecodeDone: { case kMsgDecodeDone: {
workerdata *d = (workerdata *)obj; workerdata* d = (workerdata*)obj;
AMediaCodec_stop(d->codec); AMediaCodec_stop(d->codec);
AMediaCodec_delete(d->codec); AMediaCodec_delete(d->codec);
AMediaExtractor_delete(d->ex); AMediaExtractor_delete(d->ex);
@@ -163,7 +163,7 @@ void mylooper::handle(int what, void *obj) {
} break; } break;
case kMsgSeek: { case kMsgSeek: {
workerdata *d = (workerdata *)obj; workerdata* d = (workerdata*)obj;
AMediaExtractor_seekTo(d->ex, 0, AMEDIAEXTRACTOR_SEEK_NEXT_SYNC); AMediaExtractor_seekTo(d->ex, 0, AMEDIAEXTRACTOR_SEEK_NEXT_SYNC);
AMediaCodec_flush(d->codec); AMediaCodec_flush(d->codec);
d->renderstart = -1; d->renderstart = -1;
@@ -177,7 +177,7 @@ void mylooper::handle(int what, void *obj) {
} break; } break;
case kMsgPause: { case kMsgPause: {
workerdata *d = (workerdata *)obj; workerdata* d = (workerdata*)obj;
if (d->isPlaying) { if (d->isPlaying) {
// flush all outstanding codecbuffer messages with a no-op message // flush all outstanding codecbuffer messages with a no-op message
d->isPlaying = false; d->isPlaying = false;
@@ -186,7 +186,7 @@ void mylooper::handle(int what, void *obj) {
} break; } break;
case kMsgResume: { case kMsgResume: {
workerdata *d = (workerdata *)obj; workerdata* d = (workerdata*)obj;
if (!d->isPlaying) { if (!d->isPlaying) {
d->renderstart = -1; d->renderstart = -1;
d->isPlaying = true; d->isPlaying = true;
@@ -199,11 +199,11 @@ void mylooper::handle(int what, void *obj) {
extern "C" { extern "C" {
jboolean Java_com_example_nativecodec_NativeCodec_createStreamingMediaPlayer( jboolean Java_com_example_nativecodec_NativeCodec_createStreamingMediaPlayer(
JNIEnv *env, jclass clazz, jobject assetMgr, jstring filename) { JNIEnv* env, jclass clazz, jobject assetMgr, jstring filename) {
LOGV("@@@ create"); LOGV("@@@ create");
// convert Java string to UTF-8 // convert Java string to UTF-8
const char *utf8 = env->GetStringUTFChars(filename, NULL); const char* utf8 = env->GetStringUTFChars(filename, NULL);
LOGV("opening %s", utf8); LOGV("opening %s", utf8);
off_t outStart, outLen; off_t outStart, outLen;
@@ -219,9 +219,9 @@ jboolean Java_com_example_nativecodec_NativeCodec_createStreamingMediaPlayer(
data.fd = fd; data.fd = fd;
workerdata *d = &data; workerdata* d = &data;
AMediaExtractor *ex = AMediaExtractor_new(); AMediaExtractor* ex = AMediaExtractor_new();
media_status_t err = AMediaExtractor_setDataSourceFd( media_status_t err = AMediaExtractor_setDataSourceFd(
ex, d->fd, static_cast<off64_t>(outStart), static_cast<off64_t>(outLen)); ex, d->fd, static_cast<off64_t>(outStart), static_cast<off64_t>(outLen));
close(d->fd); close(d->fd);
@@ -232,14 +232,14 @@ jboolean Java_com_example_nativecodec_NativeCodec_createStreamingMediaPlayer(
int numtracks = AMediaExtractor_getTrackCount(ex); int numtracks = AMediaExtractor_getTrackCount(ex);
AMediaCodec *codec = NULL; AMediaCodec* codec = NULL;
LOGV("input has %d tracks", numtracks); LOGV("input has %d tracks", numtracks);
for (int i = 0; i < numtracks; i++) { for (int i = 0; i < numtracks; i++) {
AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i); AMediaFormat* format = AMediaExtractor_getTrackFormat(ex, i);
const char *s = AMediaFormat_toString(format); const char* s = AMediaFormat_toString(format);
LOGV("track %d format: %s", i, s); LOGV("track %d format: %s", i, s);
const char *mime; const char* mime;
if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) { if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) {
LOGV("no mime type"); LOGV("no mime type");
return JNI_FALSE; return JNI_FALSE;
@@ -269,7 +269,7 @@ jboolean Java_com_example_nativecodec_NativeCodec_createStreamingMediaPlayer(
// set the playing state for the streaming media player // set the playing state for the streaming media player
void Java_com_example_nativecodec_NativeCodec_setPlayingStreamingMediaPlayer( void Java_com_example_nativecodec_NativeCodec_setPlayingStreamingMediaPlayer(
JNIEnv *env, jclass clazz, jboolean isPlaying) { JNIEnv* env, jclass clazz, jboolean isPlaying) {
LOGV("@@@ playpause: %d", isPlaying); LOGV("@@@ playpause: %d", isPlaying);
if (mlooper) { if (mlooper) {
if (isPlaying) { if (isPlaying) {
@@ -281,7 +281,7 @@ void Java_com_example_nativecodec_NativeCodec_setPlayingStreamingMediaPlayer(
} }
// shut down the native media system // shut down the native media system
void Java_com_example_nativecodec_NativeCodec_shutdown(JNIEnv *env, void Java_com_example_nativecodec_NativeCodec_shutdown(JNIEnv* env,
jclass clazz) { jclass clazz) {
LOGV("@@@ shutdown"); LOGV("@@@ shutdown");
if (mlooper) { if (mlooper) {
@@ -297,7 +297,7 @@ void Java_com_example_nativecodec_NativeCodec_shutdown(JNIEnv *env,
} }
// set the surface // set the surface
void Java_com_example_nativecodec_NativeCodec_setSurface(JNIEnv *env, void Java_com_example_nativecodec_NativeCodec_setSurface(JNIEnv* env,
jclass clazz, jclass clazz,
jobject surface) { jobject surface) {
// obtain a native window from a Java surface // obtain a native window from a Java surface
@@ -311,7 +311,7 @@ void Java_com_example_nativecodec_NativeCodec_setSurface(JNIEnv *env,
// rewind the streaming media player // rewind the streaming media player
void Java_com_example_nativecodec_NativeCodec_rewindStreamingMediaPlayer( void Java_com_example_nativecodec_NativeCodec_rewindStreamingMediaPlayer(
JNIEnv *env, jclass clazz) { JNIEnv* env, jclass clazz) {
LOGV("@@@ rewind"); LOGV("@@@ rewind");
if (mlooper) { if (mlooper) {
mlooper->post(kMsgSeek, &data); mlooper->post(kMsgSeek, &data);

View File

@@ -63,7 +63,7 @@ static XAVolumeItf playerVolItf = NULL;
3 // XAAndroidBufferQueueItf, XAStreamInformationItf and XAPlayItf 3 // XAAndroidBufferQueueItf, XAStreamInformationItf and XAPlayItf
// video sink for the player // video sink for the player
static ANativeWindow *theNativeWindow; static ANativeWindow* theNativeWindow;
// number of buffers in our buffer queue, an arbitrary number // number of buffers in our buffer queue, an arbitrary number
#define NB_BUFFERS 8 #define NB_BUFFERS 8
@@ -83,7 +83,7 @@ static ANativeWindow *theNativeWindow;
static char dataCache[BUFFER_SIZE * NB_BUFFERS]; static char dataCache[BUFFER_SIZE * NB_BUFFERS];
// handle of the file to play // handle of the file to play
static FILE *file; static FILE* file;
static jobject android_java_asset_manager = NULL; static jobject android_java_asset_manager = NULL;
// has the app reached the end of the file // has the app reached the end of the file
@@ -109,12 +109,12 @@ static jboolean enqueueInitialBuffers(jboolean discontinuity);
// AndroidBufferQueueItf callback to supply MPEG-2 TS packets to the media // AndroidBufferQueueItf callback to supply MPEG-2 TS packets to the media
// player // player
static XAresult AndroidBufferQueueCallback( static XAresult AndroidBufferQueueCallback(
XAAndroidBufferQueueItf caller, void *pCallbackContext, /* input */ XAAndroidBufferQueueItf caller, void* pCallbackContext, /* input */
void *pBufferContext, /* input */ void* pBufferContext, /* input */
void *pBufferData, /* input */ void* pBufferData, /* input */
XAuint32 dataSize, /* input */ XAuint32 dataSize, /* input */
XAuint32 dataUsed, /* input */ XAuint32 dataUsed, /* input */
const XAAndroidBufferItem *pItems, /* input */ const XAAndroidBufferItem* pItems, /* input */
XAuint32 itemsLength /* input */) { XAuint32 itemsLength /* input */) {
XAresult res; XAresult res;
int ok; int ok;
@@ -151,7 +151,7 @@ static XAresult AndroidBufferQueueCallback(
} }
if ((pBufferData == NULL) && (pBufferContext != NULL)) { if ((pBufferData == NULL) && (pBufferContext != NULL)) {
const int processedCommand = *(int *)pBufferContext; const int processedCommand = *(int*)pBufferContext;
if (kEosBufferCntxt == processedCommand) { if (kEosBufferCntxt == processedCommand) {
LOGV("EOS was processed\n"); LOGV("EOS was processed\n");
// our buffer with the EOS message has been consumed // our buffer with the EOS message has been consumed
@@ -162,9 +162,9 @@ static XAresult AndroidBufferQueueCallback(
// pBufferData is a pointer to a buffer that we previously Enqueued // pBufferData is a pointer to a buffer that we previously Enqueued
assert((dataSize > 0) && ((dataSize % MPEG2_TS_PACKET_SIZE) == 0)); assert((dataSize > 0) && ((dataSize % MPEG2_TS_PACKET_SIZE) == 0));
assert(dataCache <= (char *)pBufferData && assert(dataCache <= (char*)pBufferData &&
(char *)pBufferData < &dataCache[BUFFER_SIZE * NB_BUFFERS]); (char*)pBufferData < &dataCache[BUFFER_SIZE * NB_BUFFERS]);
assert(0 == (((char *)pBufferData - dataCache) % BUFFER_SIZE)); assert(0 == (((char*)pBufferData - dataCache) % BUFFER_SIZE));
// don't bother trying to read more data once we've hit EOF // don't bother trying to read more data once we've hit EOF
if (reachedEof) { if (reachedEof) {
@@ -192,9 +192,9 @@ static XAresult AndroidBufferQueueCallback(
// EOS message has no parameters, so the total size of the message is the // EOS message has no parameters, so the total size of the message is the
// size of the key // size of the key
// plus the size if itemSize, both XAuint32 // plus the size if itemSize, both XAuint32
res = (*caller)->Enqueue( res = (*caller)->Enqueue(caller, (void*)&kEosBufferCntxt /*pBufferContext*/,
caller, (void *)&kEosBufferCntxt /*pBufferContext*/, NULL /*pData*/, NULL /*pData*/, 0 /*dataLength*/, msgEos /*pMsg*/,
0 /*dataLength*/, msgEos /*pMsg*/, sizeof(XAuint32) * 2 /*msgLength*/); sizeof(XAuint32) * 2 /*msgLength*/);
assert(XA_RESULT_SUCCESS == res); assert(XA_RESULT_SUCCESS == res);
reachedEof = JNI_TRUE; reachedEof = JNI_TRUE;
} }
@@ -208,7 +208,7 @@ exit:
// callback invoked whenever there is new or changed stream information // callback invoked whenever there is new or changed stream information
static void StreamChangeCallback(XAStreamInformationItf caller, static void StreamChangeCallback(XAStreamInformationItf caller,
XAuint32 eventId, XAuint32 streamIndex, XAuint32 eventId, XAuint32 streamIndex,
void *pEventData, void *pContext) { void* pEventData, void* pContext) {
LOGV("StreamChangeCallback called for stream %u", streamIndex); LOGV("StreamChangeCallback called for stream %u", streamIndex);
// pContext was specified as NULL at RegisterStreamChangeCallback and is // pContext was specified as NULL at RegisterStreamChangeCallback and is
// unused here // unused here
@@ -250,7 +250,7 @@ static void StreamChangeCallback(XAStreamInformationItf caller,
} }
// create the engine and output mix objects // create the engine and output mix objects
void Java_com_example_nativemedia_NativeMedia_createEngine(JNIEnv *env, void Java_com_example_nativemedia_NativeMedia_createEngine(JNIEnv* env,
jclass clazz) { jclass clazz) {
XAresult res; XAresult res;
@@ -336,14 +336,14 @@ static jboolean enqueueInitialBuffers(jboolean discontinuity) {
// create streaming media player // create streaming media player
jboolean Java_com_example_nativemedia_NativeMedia_createStreamingMediaPlayer( jboolean Java_com_example_nativemedia_NativeMedia_createStreamingMediaPlayer(
JNIEnv *env, jclass clazz, jobject assetMgr, jstring filename) { JNIEnv* env, jclass clazz, jobject assetMgr, jstring filename) {
XAresult res; XAresult res;
android_java_asset_manager = (*env)->NewGlobalRef(env, assetMgr); android_java_asset_manager = (*env)->NewGlobalRef(env, assetMgr);
android_fopen_set_asset_manager( android_fopen_set_asset_manager(
AAssetManager_fromJava(env, android_java_asset_manager)); AAssetManager_fromJava(env, android_java_asset_manager));
// convert Java string to UTF-8 // convert Java string to UTF-8
const char *utf8 = (*env)->GetStringUTFChars(env, filename, NULL); const char* utf8 = (*env)->GetStringUTFChars(env, filename, NULL);
assert(NULL != utf8); assert(NULL != utf8);
// open the file to play // open the file to play
@@ -369,7 +369,7 @@ jboolean Java_com_example_nativemedia_NativeMedia_createStreamingMediaPlayer(
XA_DATALOCATOR_NATIVEDISPLAY, // locatorType XA_DATALOCATOR_NATIVEDISPLAY, // locatorType
// the video sink must be an ANativeWindow created from a Surface or // the video sink must be an ANativeWindow created from a Surface or
// SurfaceTexture // SurfaceTexture
(void *)theNativeWindow, // hWindow (void*)theNativeWindow, // hWindow
// must be NULL // must be NULL
NULL // hDisplay NULL // hDisplay
}; };
@@ -458,7 +458,7 @@ jboolean Java_com_example_nativemedia_NativeMedia_createStreamingMediaPlayer(
// set the playing state for the streaming media player // set the playing state for the streaming media player
void Java_com_example_nativemedia_NativeMedia_setPlayingStreamingMediaPlayer( void Java_com_example_nativemedia_NativeMedia_setPlayingStreamingMediaPlayer(
JNIEnv *env, jclass clazz, jboolean isPlaying) { JNIEnv* env, jclass clazz, jboolean isPlaying) {
XAresult res; XAresult res;
// make sure the streaming media player was created // make sure the streaming media player was created
@@ -472,7 +472,7 @@ void Java_com_example_nativemedia_NativeMedia_setPlayingStreamingMediaPlayer(
} }
// shut down the native media system // shut down the native media system
void Java_com_example_nativemedia_NativeMedia_shutdown(JNIEnv *env, void Java_com_example_nativemedia_NativeMedia_shutdown(JNIEnv* env,
jclass clazz) { jclass clazz) {
// destroy streaming media player object, and invalidate all associated // destroy streaming media player object, and invalidate all associated
// interfaces // interfaces
@@ -516,7 +516,7 @@ void Java_com_example_nativemedia_NativeMedia_shutdown(JNIEnv *env,
} }
// set the surface // set the surface
void Java_com_example_nativemedia_NativeMedia_setSurface(JNIEnv *env, void Java_com_example_nativemedia_NativeMedia_setSurface(JNIEnv* env,
jclass clazz, jclass clazz,
jobject surface) { jobject surface) {
// obtain a native window from a Java surface // obtain a native window from a Java surface
@@ -525,7 +525,7 @@ void Java_com_example_nativemedia_NativeMedia_setSurface(JNIEnv *env,
// rewind the streaming media player // rewind the streaming media player
void Java_com_example_nativemedia_NativeMedia_rewindStreamingMediaPlayer( void Java_com_example_nativemedia_NativeMedia_rewindStreamingMediaPlayer(
JNIEnv *env, jclass clazz) { JNIEnv* env, jclass clazz) {
XAresult res; XAresult res;
XAuint32 state; XAuint32 state;

View File

@@ -207,8 +207,9 @@ void Java_com_example_nativemidi_AppMidiManager_startWritingMidi(
void Java_com_example_nativemidi_AppMidiManager_stopWritingMidi(JNIEnv*, void Java_com_example_nativemidi_AppMidiManager_stopWritingMidi(JNIEnv*,
jobject) { jobject) {
if (sMidiInputPort != nullptr) { if (sMidiInputPort != nullptr) {
AMidiInputPort_close(sMidiInputPort); //Close InputPort to make switching MidiDevices work! AMidiInputPort_close(
sMidiInputPort = nullptr; sMidiInputPort); // Close InputPort to make switching MidiDevices work!
sMidiInputPort = nullptr;
} }
/*media_status_t status =*/AMidiDevice_release(sNativeSendDevice); /*media_status_t status =*/AMidiDevice_release(sNativeSendDevice);
sNativeSendDevice = NULL; sNativeSendDevice = NULL;

View File

@@ -61,11 +61,11 @@ typedef int32_t Fixed;
#define FIXED_FROM_INT(x) ((x) << FIXED_BITS) #define FIXED_FROM_INT(x) ((x) << FIXED_BITS)
#define FIXED_TO_INT(x) ((x) >> FIXED_BITS) #define FIXED_TO_INT(x) ((x) >> FIXED_BITS)
#define FIXED_FROM_FLOAT(x) ((Fixed)((x)*FIXED_ONE)) #define FIXED_FROM_FLOAT(x) ((Fixed)((x) * FIXED_ONE))
#define FIXED_TO_FLOAT(x) ((x) / (1. * FIXED_ONE)) #define FIXED_TO_FLOAT(x) ((x) / (1. * FIXED_ONE))
#define FIXED_MUL(x, y) (((int64_t)(x) * (y)) >> FIXED_BITS) #define FIXED_MUL(x, y) (((int64_t)(x) * (y)) >> FIXED_BITS)
#define FIXED_DIV(x, y) (((int64_t)(x)*FIXED_ONE) / (y)) #define FIXED_DIV(x, y) (((int64_t)(x) * FIXED_ONE) / (y))
#define FIXED_DIV2(x) ((x) >> 1) #define FIXED_DIV2(x) ((x) >> 1)
#define FIXED_AVERAGE(x, y) (((x) + (y)) >> 1) #define FIXED_AVERAGE(x, y) (((x) + (y)) >> 1)
@@ -88,8 +88,8 @@ typedef int32_t Angle;
#define ANGLE_PI2 (1 << (ANGLE_BITS - 2)) #define ANGLE_PI2 (1 << (ANGLE_BITS - 2))
#define ANGLE_PI4 (1 << (ANGLE_BITS - 3)) #define ANGLE_PI4 (1 << (ANGLE_BITS - 3))
#define ANGLE_FROM_FLOAT(x) (Angle)((x)*ANGLE_PI / M_PI) #define ANGLE_FROM_FLOAT(x) (Angle)((x) * ANGLE_PI / M_PI)
#define ANGLE_TO_FLOAT(x) ((x)*M_PI / ANGLE_PI) #define ANGLE_TO_FLOAT(x) ((x) * M_PI / ANGLE_PI)
#if ANGLE_BITS <= FIXED_BITS #if ANGLE_BITS <= FIXED_BITS
#define ANGLE_FROM_FIXED(x) (Angle)((x) >> (FIXED_BITS - ANGLE_BITS)) #define ANGLE_FROM_FIXED(x) (Angle)((x) >> (FIXED_BITS - ANGLE_BITS))
@@ -459,7 +459,7 @@ void android_main(struct android_app* state) {
// to draw the next frame of animation. // to draw the next frame of animation.
struct android_poll_source* source = NULL; struct android_poll_source* source = NULL;
int result = ALooper_pollOnce(engine.animating ? 0 : -1, NULL, NULL, int result = ALooper_pollOnce(engine.animating ? 0 : -1, NULL, NULL,
(void**)&source); (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");
abort(); abort();

View File

@@ -28,14 +28,14 @@
#include "simple_model.h" #include "simple_model.h"
extern "C" JNIEXPORT jlong JNICALL extern "C" JNIEXPORT jlong JNICALL
Java_com_example_android_basic_MainActivity_initModel(JNIEnv *env, Java_com_example_android_basic_MainActivity_initModel(JNIEnv* env,
jobject /* this */, jobject /* this */,
jobject _assetManager, jobject _assetManager,
jstring _assetName) { jstring _assetName) {
// Get the file descriptor of the model data file. // Get the file descriptor of the model data file.
AAssetManager *assetManager = AAssetManager_fromJava(env, _assetManager); AAssetManager* assetManager = AAssetManager_fromJava(env, _assetManager);
const char *assetName = env->GetStringUTFChars(_assetName, NULL); const char* assetName = env->GetStringUTFChars(_assetName, NULL);
AAsset *asset = AAsset* asset =
AAssetManager_open(assetManager, assetName, AASSET_MODE_BUFFER); AAssetManager_open(assetManager, assetName, AASSET_MODE_BUFFER);
if (asset == nullptr) { if (asset == nullptr) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
@@ -43,7 +43,7 @@ Java_com_example_android_basic_MainActivity_initModel(JNIEnv *env,
return 0; return 0;
} }
env->ReleaseStringUTFChars(_assetName, assetName); env->ReleaseStringUTFChars(_assetName, assetName);
SimpleModel *nn_model = new SimpleModel(asset); SimpleModel* nn_model = new SimpleModel(asset);
AAsset_close(asset); AAsset_close(asset);
if (!nn_model->CreateCompiledModel()) { if (!nn_model->CreateCompiledModel()) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
@@ -55,21 +55,21 @@ Java_com_example_android_basic_MainActivity_initModel(JNIEnv *env,
} }
extern "C" JNIEXPORT jfloat JNICALL extern "C" JNIEXPORT jfloat JNICALL
Java_com_example_android_basic_MainActivity_startCompute(JNIEnv *env, Java_com_example_android_basic_MainActivity_startCompute(JNIEnv* env,
jobject /* this */, jobject /* this */,
jlong _nnModel, jlong _nnModel,
jfloat inputValue1, jfloat inputValue1,
jfloat inputValue2) { jfloat inputValue2) {
SimpleModel *nn_model = (SimpleModel *)_nnModel; SimpleModel* nn_model = (SimpleModel*)_nnModel;
float result = 0.0f; float result = 0.0f;
nn_model->Compute(inputValue1, inputValue2, &result); nn_model->Compute(inputValue1, inputValue2, &result);
return result; return result;
} }
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_example_android_basic_MainActivity_destroyModel(JNIEnv *env, Java_com_example_android_basic_MainActivity_destroyModel(JNIEnv* env,
jobject /* this */, jobject /* this */,
jlong _nnModel) { jlong _nnModel) {
SimpleModel *nn_model = (SimpleModel *)_nnModel; SimpleModel* nn_model = (SimpleModel*)_nnModel;
delete (nn_model); delete (nn_model);
} }

View File

@@ -32,7 +32,7 @@ namespace {
// 1. Allocate a large-enough shared memory to hold the model data; // 1. Allocate a large-enough shared memory to hold the model data;
// 2. Copy the asset file to the shared memory; // 2. Copy the asset file to the shared memory;
// 3. Create the NNAPI memory with the file descriptor of the shared memory. // 3. Create the NNAPI memory with the file descriptor of the shared memory.
ANeuralNetworksMemory *createMemoryFromAsset(AAsset *asset) { ANeuralNetworksMemory* createMemoryFromAsset(AAsset* asset) {
// Allocate a large-enough shared memory to hold the model data. // Allocate a large-enough shared memory to hold the model data.
off_t length = AAsset_getLength(asset); off_t length = AAsset_getLength(asset);
int fd = ASharedMemory_create("model_data", length); int fd = ASharedMemory_create("model_data", length);
@@ -43,7 +43,7 @@ ANeuralNetworksMemory *createMemoryFromAsset(AAsset *asset) {
} }
// Copy the asset file to the shared memory. // Copy the asset file to the shared memory.
void *data = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); void* data = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (data == nullptr) { if (data == nullptr) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
"Failed to map a shared memory"); "Failed to map a shared memory");
@@ -54,7 +54,7 @@ ANeuralNetworksMemory *createMemoryFromAsset(AAsset *asset) {
munmap(data, length); munmap(data, length);
// Create the NNAPI memory with the file descriptor of the shared memory. // Create the NNAPI memory with the file descriptor of the shared memory.
ANeuralNetworksMemory *memory; ANeuralNetworksMemory* memory;
int status = ANeuralNetworksMemory_createFromFd( int status = ANeuralNetworksMemory_createFromFd(
length, PROT_READ | PROT_WRITE, fd, 0, &memory); length, PROT_READ | PROT_WRITE, fd, 0, &memory);
@@ -77,7 +77,7 @@ ANeuralNetworksMemory *createMemoryFromAsset(AAsset *asset) {
* *
* Initialize the member variables, including the shared memory objects. * Initialize the member variables, including the shared memory objects.
*/ */
SimpleModel::SimpleModel(AAsset *asset) SimpleModel::SimpleModel(AAsset* asset)
: model_(nullptr), compilation_(nullptr), dimLength_(TENSOR_SIZE) { : model_(nullptr), compilation_(nullptr), dimLength_(TENSOR_SIZE) {
tensorSize_ = dimLength_; tensorSize_ = dimLength_;
inputTensor1_.resize(tensorSize_); inputTensor1_.resize(tensorSize_);
@@ -422,7 +422,7 @@ bool SimpleModel::CreateCompiledModel() {
* inputValue2: The values to fill tensor3 * inputValue2: The values to fill tensor3
* @return computed result, or 0.0f if there is error. * @return computed result, or 0.0f if there is error.
*/ */
bool SimpleModel::Compute(float inputValue1, float inputValue2, float *result) { bool SimpleModel::Compute(float inputValue1, float inputValue2, float* result) {
if (!result) { if (!result) {
return false; return false;
} }
@@ -434,7 +434,7 @@ bool SimpleModel::Compute(float inputValue1, float inputValue2, float *result) {
// 2. Multiple concurrent execution instances could be created from the same // 2. Multiple concurrent execution instances could be created from the same
// compiled model. // compiled model.
// This sample only uses one execution of the compiled model. // This sample only uses one execution of the compiled model.
ANeuralNetworksExecution *execution; ANeuralNetworksExecution* execution;
int32_t status = ANeuralNetworksExecution_create(compilation_, &execution); int32_t status = ANeuralNetworksExecution_create(compilation_, &execution);
if (status != ANEURALNETWORKS_NO_ERROR) { if (status != ANEURALNETWORKS_NO_ERROR) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
@@ -462,7 +462,7 @@ bool SimpleModel::Compute(float inputValue1, float inputValue2, float *result) {
// Set the values of the second input operand (tensor3) to be inputValue2. // Set the values of the second input operand (tensor3) to be inputValue2.
// In reality, the values in the shared memory region will be manipulated by // In reality, the values in the shared memory region will be manipulated by
// other modules or processes. // other modules or processes.
float *inputTensor2Ptr = reinterpret_cast<float *>( float* inputTensor2Ptr = reinterpret_cast<float*>(
mmap(nullptr, tensorSize_ * sizeof(float), PROT_READ | PROT_WRITE, mmap(nullptr, tensorSize_ * sizeof(float), PROT_READ | PROT_WRITE,
MAP_SHARED, inputTensor2Fd_, 0)); MAP_SHARED, inputTensor2Fd_, 0));
for (int i = 0; i < tensorSize_; i++) { for (int i = 0; i < tensorSize_; i++) {
@@ -499,7 +499,7 @@ bool SimpleModel::Compute(float inputValue1, float inputValue2, float *result) {
// Start the execution of the model. // Start the execution of the model.
// Note that the execution here is asynchronous, and an ANeuralNetworksEvent // Note that the execution here is asynchronous, and an ANeuralNetworksEvent
// object will be created to monitor the status of the execution. // object will be created to monitor the status of the execution.
ANeuralNetworksEvent *event = nullptr; ANeuralNetworksEvent* event = nullptr;
status = ANeuralNetworksExecution_startCompute(execution, &event); status = ANeuralNetworksExecution_startCompute(execution, &event);
if (status != ANEURALNETWORKS_NO_ERROR) { if (status != ANEURALNETWORKS_NO_ERROR) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
@@ -522,9 +522,9 @@ bool SimpleModel::Compute(float inputValue1, float inputValue2, float *result) {
// Validate the results. // Validate the results.
const float goldenRef = (inputValue1 + 0.5f) * (inputValue2 + 0.5f); const float goldenRef = (inputValue1 + 0.5f) * (inputValue2 + 0.5f);
float *outputTensorPtr = reinterpret_cast<float *>( float* outputTensorPtr =
mmap(nullptr, tensorSize_ * sizeof(float), PROT_READ, MAP_SHARED, reinterpret_cast<float*>(mmap(nullptr, tensorSize_ * sizeof(float),
outputTensorFd_, 0)); PROT_READ, MAP_SHARED, outputTensorFd_, 0));
for (int32_t idx = 0; idx < tensorSize_; idx++) { for (int32_t idx = 0; idx < tensorSize_; idx++) {
float delta = outputTensorPtr[idx] - goldenRef; float delta = outputTensorPtr[idx] - goldenRef;
delta = (delta < 0.0f) ? (-delta) : delta; delta = (delta < 0.0f) ? (-delta) : delta;

View File

@@ -40,18 +40,18 @@
*/ */
class SimpleModel { class SimpleModel {
public: public:
explicit SimpleModel(AAsset *asset); explicit SimpleModel(AAsset* asset);
~SimpleModel(); ~SimpleModel();
bool CreateCompiledModel(); bool CreateCompiledModel();
bool Compute(float inputValue1, float inputValue2, float *result); bool Compute(float inputValue1, float inputValue2, float* result);
private: private:
ANeuralNetworksModel *model_; ANeuralNetworksModel* model_;
ANeuralNetworksCompilation *compilation_; ANeuralNetworksCompilation* compilation_;
ANeuralNetworksMemory *memoryModel_; ANeuralNetworksMemory* memoryModel_;
ANeuralNetworksMemory *memoryInput2_; ANeuralNetworksMemory* memoryInput2_;
ANeuralNetworksMemory *memoryOutput_; ANeuralNetworksMemory* memoryOutput_;
uint32_t dimLength_; uint32_t dimLength_;
uint32_t tensorSize_; uint32_t tensorSize_;

View File

@@ -8,12 +8,12 @@
const char kLogTag[] = "orderfiledemo"; const char kLogTag[] = "orderfiledemo";
#ifdef GENERATE_PROFILES #ifdef GENERATE_PROFILES
extern "C" int __llvm_profile_set_filename(const char *); extern "C" int __llvm_profile_set_filename(const char*);
extern "C" int __llvm_profile_initialize_file(void); extern "C" int __llvm_profile_initialize_file(void);
extern "C" int __llvm_orderfile_dump(void); extern "C" int __llvm_orderfile_dump(void);
#endif #endif
void DumpProfileDataIfNeeded(const char *temp_dir) { void DumpProfileDataIfNeeded(const char* temp_dir) {
#ifdef GENERATE_PROFILES #ifdef GENERATE_PROFILES
char profile_location[PATH_MAX] = {}; char profile_location[PATH_MAX] = {};
snprintf(profile_location, sizeof(profile_location), "%s/demo.output", snprintf(profile_location, sizeof(profile_location), "%s/demo.output",
@@ -47,7 +47,7 @@ void DumpProfileDataIfNeeded(const char *temp_dir) {
} }
extern "C" JNIEXPORT void JNICALL extern "C" JNIEXPORT void JNICALL
Java_com_example_orderfiledemo_MainActivity_runWorkload(JNIEnv *env, Java_com_example_orderfiledemo_MainActivity_runWorkload(JNIEnv* env,
jobject /* this */, jobject /* this */,
jstring temp_dir) { jstring temp_dir) {
DumpProfileDataIfNeeded(env->GetStringUTFChars(temp_dir, 0)); DumpProfileDataIfNeeded(env->GetStringUTFChars(temp_dir, 0));

View File

@@ -26,7 +26,7 @@ namespace jsonparse {
extern "C" JNIEXPORT jstring JNICALL extern "C" JNIEXPORT jstring JNICALL
Java_com_example_prefabdependency_MainActivity_getJsonValue( Java_com_example_prefabdependency_MainActivity_getJsonValue(
JNIEnv *env, jobject /* this */, jstring jsonFromJava, JNIEnv* env, jobject /* this */, jstring jsonFromJava,
jstring keyFromJava) { jstring keyFromJava) {
if (jsonFromJava == nullptr) { if (jsonFromJava == nullptr) {
logging::FatalError(env, "jsonFromJava argument cannot be null"); logging::FatalError(env, "jsonFromJava argument cannot be null");

View File

@@ -68,9 +68,9 @@ typedef struct {
* components per color with GL_UNSIGNED_BYTE datatype and stride 0. * components per color with GL_UNSIGNED_BYTE datatype and stride 0.
* Normal array is supposed to use GL_FIXED datatype and stride 0. * Normal array is supposed to use GL_FIXED datatype and stride 0.
*/ */
GLfixed *vertexArray; GLfixed* vertexArray;
GLubyte *colorArray; GLubyte* colorArray;
GLfixed *normalArray; GLfixed* normalArray;
GLint vertexComponents; GLint vertexComponents;
GLsizei count; GLsizei count;
} GLOBJECT; } GLOBJECT;
@@ -82,14 +82,14 @@ static int sCurrentCamTrack = 0;
static long sCurrentCamTrackStartTick = 0; static long sCurrentCamTrackStartTick = 0;
static long sNextCamTrackStartTick = 0x7fffffff; static long sNextCamTrackStartTick = 0x7fffffff;
static GLOBJECT *sSuperShapeObjects[SUPERSHAPE_COUNT] = {NULL}; static GLOBJECT* sSuperShapeObjects[SUPERSHAPE_COUNT] = {NULL};
static GLOBJECT *sGroundPlane = NULL; static GLOBJECT* sGroundPlane = NULL;
typedef struct { typedef struct {
float x, y, z; float x, y, z;
} VECTOR3; } VECTOR3;
static void freeGLObject(GLOBJECT *object) { static void freeGLObject(GLOBJECT* object) {
if (object == NULL) return; if (object == NULL) return;
free(object->normalArray); free(object->normalArray);
free(object->colorArray); free(object->colorArray);
@@ -97,18 +97,18 @@ static void freeGLObject(GLOBJECT *object) {
free(object); free(object);
} }
static GLOBJECT *newGLObject(long vertices, int vertexComponents, static GLOBJECT* newGLObject(long vertices, int vertexComponents,
int useNormalArray) { int useNormalArray) {
GLOBJECT *result; GLOBJECT* result;
result = (GLOBJECT *)malloc(sizeof(GLOBJECT)); result = (GLOBJECT*)malloc(sizeof(GLOBJECT));
if (result == NULL) return NULL; if (result == NULL) return NULL;
result->count = vertices; result->count = vertices;
result->vertexComponents = vertexComponents; result->vertexComponents = vertexComponents;
result->vertexArray = result->vertexArray =
(GLfixed *)malloc(vertices * vertexComponents * sizeof(GLfixed)); (GLfixed*)malloc(vertices * vertexComponents * sizeof(GLfixed));
result->colorArray = (GLubyte *)malloc(vertices * 4 * sizeof(GLubyte)); result->colorArray = (GLubyte*)malloc(vertices * 4 * sizeof(GLubyte));
if (useNormalArray) { if (useNormalArray) {
result->normalArray = (GLfixed *)malloc(vertices * 3 * sizeof(GLfixed)); result->normalArray = (GLfixed*)malloc(vertices * 3 * sizeof(GLfixed));
} else } else
result->normalArray = NULL; result->normalArray = NULL;
if (result->vertexArray == NULL || result->colorArray == NULL || if (result->vertexArray == NULL || result->colorArray == NULL ||
@@ -119,7 +119,7 @@ static GLOBJECT *newGLObject(long vertices, int vertexComponents,
return result; return result;
} }
static void drawGLObject(GLOBJECT *object) { static void drawGLObject(GLOBJECT* object) {
assert(object != NULL); assert(object != NULL);
glVertexPointer(object->vertexComponents, GL_FIXED, 0, object->vertexArray); glVertexPointer(object->vertexComponents, GL_FIXED, 0, object->vertexArray);
@@ -137,13 +137,13 @@ static void drawGLObject(GLOBJECT *object) {
glDrawArrays(GL_TRIANGLES, 0, object->count); glDrawArrays(GL_TRIANGLES, 0, object->count);
} }
static void vector3Sub(VECTOR3 *dest, VECTOR3 *v1, VECTOR3 *v2) { static void vector3Sub(VECTOR3* dest, VECTOR3* v1, VECTOR3* v2) {
dest->x = v1->x - v2->x; dest->x = v1->x - v2->x;
dest->y = v1->y - v2->y; dest->y = v1->y - v2->y;
dest->z = v1->z - v2->z; dest->z = v1->z - v2->z;
} }
static void superShapeMap(VECTOR3 *point, float r1, float r2, float t, static void superShapeMap(VECTOR3* point, float r1, float r2, float t,
float p) { float p) {
// sphere-mapping of supershape parameters // sphere-mapping of supershape parameters
point->x = (float)(cos(t) * cos(p) / r1 / r2); point->x = (float)(cos(t) * cos(p) / r1 / r2);
@@ -151,7 +151,7 @@ static void superShapeMap(VECTOR3 *point, float r1, float r2, float t,
point->z = (float)(sin(p) / r2); point->z = (float)(sin(p) / r2);
} }
static float ssFunc(const float t, const float *p) { static float ssFunc(const float t, const float* p) {
return (float)(pow(pow(fabs(cos(p[0] * t / 4)) / p[1], p[4]) + return (float)(pow(pow(fabs(cos(p[0] * t / 4)) / p[1], p[4]) +
pow(fabs(sin(p[0] * t / 4)) / p[2], p[5]), pow(fabs(sin(p[0] * t / 4)) / p[2], p[5]),
1 / p[3])); 1 / p[3]));
@@ -160,7 +160,7 @@ static float ssFunc(const float t, const float *p) {
// Creates and returns a supershape object. // Creates and returns a supershape object.
// Based on Paul Bourke's POV-Ray implementation. // Based on Paul Bourke's POV-Ray implementation.
// http://astronomy.swin.edu.au/~pbourke/povray/supershape/ // http://astronomy.swin.edu.au/~pbourke/povray/supershape/
static GLOBJECT *createSuperShape(const float *params) { static GLOBJECT* createSuperShape(const float* params) {
const int resol1 = (int)params[SUPERSHAPE_PARAMS - 3]; const int resol1 = (int)params[SUPERSHAPE_PARAMS - 3];
const int resol2 = (int)params[SUPERSHAPE_PARAMS - 2]; const int resol2 = (int)params[SUPERSHAPE_PARAMS - 2];
// latitude 0 to pi/2 for no mirrored bottom // latitude 0 to pi/2 for no mirrored bottom
@@ -171,7 +171,7 @@ static GLOBJECT *createSuperShape(const float *params) {
const int latitudeCount = latitudeEnd - latitudeBegin; const int latitudeCount = latitudeEnd - latitudeBegin;
const long triangleCount = longitudeCount * latitudeCount * 2; const long triangleCount = longitudeCount * latitudeCount * 2;
const long vertices = triangleCount * 3; const long vertices = triangleCount * 3;
GLOBJECT *result; GLOBJECT* result;
float baseColor[3]; float baseColor[3];
int a, longitude, latitude; int a, longitude, latitude;
long currentVertex; long currentVertex;
@@ -283,7 +283,7 @@ static GLOBJECT *createSuperShape(const float *params) {
++currentVertex; ++currentVertex;
} // r0 && r1 && r2 && r3 } // r0 && r1 && r2 && r3
} // latitude } // latitude
} // longitude } // longitude
// Set number of vertices in object to the actual amount created. // Set number of vertices in object to the actual amount created.
result->count = currentVertex; result->count = currentVertex;
@@ -291,13 +291,13 @@ static GLOBJECT *createSuperShape(const float *params) {
return result; return result;
} }
static GLOBJECT *createGroundPlane() { static GLOBJECT* createGroundPlane() {
const int scale = 4; const int scale = 4;
const int yBegin = -15, yEnd = 15; // ends are non-inclusive const int yBegin = -15, yEnd = 15; // ends are non-inclusive
const int xBegin = -15, xEnd = 15; const int xBegin = -15, xEnd = 15;
const long triangleCount = (yEnd - yBegin) * (xEnd - xBegin) * 2; const long triangleCount = (yEnd - yBegin) * (xEnd - xBegin) * 2;
const long vertices = triangleCount * 3; const long vertices = triangleCount * 3;
GLOBJECT *result; GLOBJECT* result;
int x, y; int x, y;
long currentVertex; long currentVertex;
@@ -608,7 +608,7 @@ static void camTrack() {
float lerp[5]; float lerp[5];
float eX, eY, eZ, cX, cY, cZ; float eX, eY, eZ, cX, cY, cZ;
float trackPos; float trackPos;
CAMTRACK *cam; CAMTRACK* cam;
long currentCamTick; long currentCamTick;
int a; int a;

View File

@@ -44,7 +44,7 @@ static HMODULE sGLESDLL = NULL;
#ifdef LINUX #ifdef LINUX
#include <dlfcn.h> #include <dlfcn.h>
#include <stdlib.h> #include <stdlib.h>
static void *sGLESSO = NULL; static void* sGLESSO = NULL;
#endif // LINUX #endif // LINUX
#endif /* DISABLE_IMPORTGL */ #endif /* DISABLE_IMPORTGL */
@@ -78,11 +78,11 @@ int importGLInit() {
* void * results in warnings with VC warning level 4, which * void * results in warnings with VC warning level 4, which
* could be fixed by casting to the true type for each fetch. * could be fixed by casting to the true type for each fetch.
*/ */
#define IMPORT_FUNC(funcName) \ #define IMPORT_FUNC(funcName) \
do { \ do { \
void *procAddress = (void *)GetProcAddress(sGLESDLL, _T(#funcName)); \ void* procAddress = (void*)GetProcAddress(sGLESDLL, _T(#funcName)); \
if (procAddress == NULL) result = 0; \ if (procAddress == NULL) result = 0; \
*((void **)&FNPTR(funcName)) = procAddress; \ *((void**)&FNPTR(funcName)) = procAddress; \
} while (0) } while (0)
#endif // WIN32 #endif // WIN32
@@ -96,11 +96,11 @@ int importGLInit() {
if (sGLESSO == NULL) if (sGLESSO == NULL)
return 0; // Cannot find OpenGL ES Common or Common Lite SO. return 0; // Cannot find OpenGL ES Common or Common Lite SO.
#define IMPORT_FUNC(funcName) \ #define IMPORT_FUNC(funcName) \
do { \ do { \
void *procAddress = (void *)dlsym(sGLESSO, #funcName); \ void* procAddress = (void*)dlsym(sGLESSO, #funcName); \
if (procAddress == NULL) result = 0; \ if (procAddress == NULL) result = 0; \
*((void **)&FNPTR(funcName)) = procAddress; \ *((void**)&FNPTR(funcName)) = procAddress; \
} while (0) } while (0)
#endif // LINUX #endif // LINUX

View File

@@ -61,25 +61,25 @@ extern void importGLDeinit();
#ifndef ANDROID_NDK #ifndef ANDROID_NDK
FNDEF(EGLBoolean, eglChooseConfig, FNDEF(EGLBoolean, eglChooseConfig,
(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, (EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs,
EGLint config_size, EGLint *num_config)); EGLint config_size, EGLint* num_config));
FNDEF(EGLContext, eglCreateContext, FNDEF(EGLContext, eglCreateContext,
(EGLDisplay dpy, EGLConfig config, EGLContext share_list, (EGLDisplay dpy, EGLConfig config, EGLContext share_list,
const EGLint *attrib_list)); const EGLint* attrib_list));
FNDEF(EGLSurface, eglCreateWindowSurface, FNDEF(EGLSurface, eglCreateWindowSurface,
(EGLDisplay dpy, EGLConfig config, NativeWindowType window, (EGLDisplay dpy, EGLConfig config, NativeWindowType window,
const EGLint *attrib_list)); const EGLint* attrib_list));
FNDEF(EGLBoolean, eglDestroyContext, (EGLDisplay dpy, EGLContext ctx)); FNDEF(EGLBoolean, eglDestroyContext, (EGLDisplay dpy, EGLContext ctx));
FNDEF(EGLBoolean, eglDestroySurface, (EGLDisplay dpy, EGLSurface surface)); FNDEF(EGLBoolean, eglDestroySurface, (EGLDisplay dpy, EGLSurface surface));
FNDEF(EGLBoolean, eglGetConfigAttrib, FNDEF(EGLBoolean, eglGetConfigAttrib,
(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value)); (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value));
FNDEF(EGLBoolean, eglGetConfigs, FNDEF(EGLBoolean, eglGetConfigs,
(EGLDisplay dpy, EGLConfig *configs, EGLint config_size, (EGLDisplay dpy, EGLConfig* configs, EGLint config_size,
EGLint *num_config)); EGLint* num_config));
FNDEF(EGLDisplay, eglGetDisplay, (NativeDisplayType display)); FNDEF(EGLDisplay, eglGetDisplay, (NativeDisplayType display));
FNDEF(EGLint, eglGetError, (void)); FNDEF(EGLint, eglGetError, (void));
FNDEF(EGLBoolean, eglInitialize, FNDEF(EGLBoolean, eglInitialize,
(EGLDisplay dpy, EGLint *major, EGLint *minor)); (EGLDisplay dpy, EGLint* major, EGLint* minor));
FNDEF(EGLBoolean, eglMakeCurrent, FNDEF(EGLBoolean, eglMakeCurrent,
(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx)); (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx));
FNDEF(EGLBoolean, eglSwapBuffers, (EGLDisplay dpy, EGLSurface draw)); FNDEF(EGLBoolean, eglSwapBuffers, (EGLDisplay dpy, EGLSurface draw));
@@ -93,7 +93,7 @@ FNDEF(void, glClearColorx,
FNDEF(void, glColor4x, FNDEF(void, glColor4x,
(GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha)); (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha));
FNDEF(void, glColorPointer, FNDEF(void, glColorPointer,
(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)); (GLint size, GLenum type, GLsizei stride, const GLvoid* pointer));
FNDEF(void, glDisable, (GLenum cap)); FNDEF(void, glDisable, (GLenum cap));
FNDEF(void, glDisableClientState, (GLenum array)); FNDEF(void, glDisableClientState, (GLenum array));
FNDEF(void, glDrawArrays, (GLenum mode, GLint first, GLsizei count)); FNDEF(void, glDrawArrays, (GLenum mode, GLint first, GLsizei count));
@@ -103,14 +103,14 @@ FNDEF(void, glFrustumx,
(GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, (GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear,
GLfixed zFar)); GLfixed zFar));
FNDEF(GLenum, glGetError, (void)); FNDEF(GLenum, glGetError, (void));
FNDEF(void, glLightxv, (GLenum light, GLenum pname, const GLfixed *params)); FNDEF(void, glLightxv, (GLenum light, GLenum pname, const GLfixed* params));
FNDEF(void, glLoadIdentity, (void)); FNDEF(void, glLoadIdentity, (void));
FNDEF(void, glMaterialx, (GLenum face, GLenum pname, GLfixed param)); FNDEF(void, glMaterialx, (GLenum face, GLenum pname, GLfixed param));
FNDEF(void, glMaterialxv, (GLenum face, GLenum pname, const GLfixed *params)); FNDEF(void, glMaterialxv, (GLenum face, GLenum pname, const GLfixed* params));
FNDEF(void, glMatrixMode, (GLenum mode)); FNDEF(void, glMatrixMode, (GLenum mode));
FNDEF(void, glMultMatrixx, (const GLfixed *m)); FNDEF(void, glMultMatrixx, (const GLfixed* m));
FNDEF(void, glNormalPointer, FNDEF(void, glNormalPointer,
(GLenum type, GLsizei stride, const GLvoid *pointer)); (GLenum type, GLsizei stride, const GLvoid* pointer));
FNDEF(void, glPopMatrix, (void)); FNDEF(void, glPopMatrix, (void));
FNDEF(void, glPushMatrix, (void)); FNDEF(void, glPushMatrix, (void));
FNDEF(void, glRotatex, (GLfixed angle, GLfixed x, GLfixed y, GLfixed z)); FNDEF(void, glRotatex, (GLfixed angle, GLfixed x, GLfixed y, GLfixed z));
@@ -118,7 +118,7 @@ FNDEF(void, glScalex, (GLfixed x, GLfixed y, GLfixed z));
FNDEF(void, glShadeModel, (GLenum mode)); FNDEF(void, glShadeModel, (GLenum mode));
FNDEF(void, glTranslatex, (GLfixed x, GLfixed y, GLfixed z)); FNDEF(void, glTranslatex, (GLfixed x, GLfixed y, GLfixed z));
FNDEF(void, glVertexPointer, FNDEF(void, glVertexPointer,
(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)); (GLint size, GLenum type, GLsizei stride, const GLvoid* pointer));
FNDEF(void, glViewport, (GLint x, GLint y, GLsizei width, GLsizei height)); FNDEF(void, glViewport, (GLint x, GLint y, GLsizei width, GLsizei height));
#undef FN #undef FN

View File

@@ -42,10 +42,10 @@ const float SENSOR_FILTER_ALPHA = 0.1f;
* for Android-N and before, when compiling with NDK-r15 * for Android-N and before, when compiling with NDK-r15
*/ */
#include <dlfcn.h> #include <dlfcn.h>
const char *kPackageName = "com.android.accelerometergraph"; const char* kPackageName = "com.android.accelerometergraph";
ASensorManager *AcquireASensorManagerInstance(void) { ASensorManager* AcquireASensorManagerInstance(void) {
typedef ASensorManager *(*PF_GETINSTANCEFORPACKAGE)(const char *name); typedef ASensorManager* (*PF_GETINSTANCEFORPACKAGE)(const char* name);
void *androidHandle = dlopen("libandroid.so", RTLD_NOW); void* androidHandle = dlopen("libandroid.so", RTLD_NOW);
PF_GETINSTANCEFORPACKAGE getInstanceForPackageFunc = PF_GETINSTANCEFORPACKAGE getInstanceForPackageFunc =
(PF_GETINSTANCEFORPACKAGE)dlsym(androidHandle, (PF_GETINSTANCEFORPACKAGE)dlsym(androidHandle,
"ASensorManager_getInstanceForPackage"); "ASensorManager_getInstanceForPackage");
@@ -53,7 +53,7 @@ ASensorManager *AcquireASensorManagerInstance(void) {
return getInstanceForPackageFunc(kPackageName); return getInstanceForPackageFunc(kPackageName);
} }
typedef ASensorManager *(*PF_GETINSTANCE)(); typedef ASensorManager* (*PF_GETINSTANCE)();
PF_GETINSTANCE getInstanceFunc = PF_GETINSTANCE getInstanceFunc =
(PF_GETINSTANCE)dlsym(androidHandle, "ASensorManager_getInstance"); (PF_GETINSTANCE)dlsym(androidHandle, "ASensorManager_getInstance");
// by all means at this point, ASensorManager_getInstance should be available // by all means at this point, ASensorManager_getInstance should be available
@@ -64,10 +64,10 @@ ASensorManager *AcquireASensorManagerInstance(void) {
class sensorgraph { class sensorgraph {
std::string vertexShaderSource; std::string vertexShaderSource;
std::string fragmentShaderSource; std::string fragmentShaderSource;
ASensorManager *sensorManager; ASensorManager* sensorManager;
const ASensor *accelerometer; const ASensor* accelerometer;
ASensorEventQueue *accelerometerEventQueue; ASensorEventQueue* accelerometerEventQueue;
ALooper *looper; ALooper* looper;
GLuint shaderProgram; GLuint shaderProgram;
GLuint vPositionHandle; GLuint vPositionHandle;
@@ -87,24 +87,24 @@ class sensorgraph {
public: public:
sensorgraph() : sensorDataIndex(0) {} sensorgraph() : sensorDataIndex(0) {}
void init(AAssetManager *assetManager) { void init(AAssetManager* assetManager) {
AAsset *vertexShaderAsset = AAsset* vertexShaderAsset =
AAssetManager_open(assetManager, "shader.glslv", AASSET_MODE_BUFFER); AAssetManager_open(assetManager, "shader.glslv", AASSET_MODE_BUFFER);
assert(vertexShaderAsset != NULL); assert(vertexShaderAsset != NULL);
const void *vertexShaderBuf = AAsset_getBuffer(vertexShaderAsset); const void* vertexShaderBuf = AAsset_getBuffer(vertexShaderAsset);
assert(vertexShaderBuf != NULL); assert(vertexShaderBuf != NULL);
off_t vertexShaderLength = AAsset_getLength(vertexShaderAsset); off_t vertexShaderLength = AAsset_getLength(vertexShaderAsset);
vertexShaderSource = vertexShaderSource =
std::string((const char *)vertexShaderBuf, (size_t)vertexShaderLength); std::string((const char*)vertexShaderBuf, (size_t)vertexShaderLength);
AAsset_close(vertexShaderAsset); AAsset_close(vertexShaderAsset);
AAsset *fragmentShaderAsset = AAsset* fragmentShaderAsset =
AAssetManager_open(assetManager, "shader.glslf", AASSET_MODE_BUFFER); AAssetManager_open(assetManager, "shader.glslf", AASSET_MODE_BUFFER);
assert(fragmentShaderAsset != NULL); assert(fragmentShaderAsset != NULL);
const void *fragmentShaderBuf = AAsset_getBuffer(fragmentShaderAsset); const void* fragmentShaderBuf = AAsset_getBuffer(fragmentShaderAsset);
assert(fragmentShaderBuf != NULL); assert(fragmentShaderBuf != NULL);
off_t fragmentShaderLength = AAsset_getLength(fragmentShaderAsset); off_t fragmentShaderLength = AAsset_getLength(fragmentShaderAsset);
fragmentShaderSource = std::string((const char *)fragmentShaderBuf, fragmentShaderSource = std::string((const char*)fragmentShaderBuf,
(size_t)fragmentShaderLength); (size_t)fragmentShaderLength);
AAsset_close(fragmentShaderAsset); AAsset_close(fragmentShaderAsset);
@@ -161,8 +161,8 @@ class sensorgraph {
} }
} }
GLuint createProgram(const std::string &pVertexSource, GLuint createProgram(const std::string& pVertexSource,
const std::string &pFragmentSource) { const std::string& pFragmentSource) {
GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource); GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource); GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
GLuint program = glCreateProgram(); GLuint program = glCreateProgram();
@@ -178,10 +178,10 @@ class sensorgraph {
return program; return program;
} }
GLuint loadShader(GLenum shaderType, const std::string &pSource) { GLuint loadShader(GLenum shaderType, const std::string& pSource) {
GLuint shader = glCreateShader(shaderType); GLuint shader = glCreateShader(shaderType);
assert(shader != 0); assert(shader != 0);
const char *sourceBuf = pSource.c_str(); const char* sourceBuf = pSource.c_str();
glShaderSource(shader, 1, &sourceBuf, NULL); glShaderSource(shader, 1, &sourceBuf, NULL);
glCompileShader(shader); glCompileShader(shader);
GLint shaderCompiled = 0; GLint shaderCompiled = 0;
@@ -255,15 +255,15 @@ sensorgraph gSensorGraph;
extern "C" { extern "C" {
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_android_accelerometergraph_AccelerometerGraphJNI_init( Java_com_android_accelerometergraph_AccelerometerGraphJNI_init(
JNIEnv *env, jclass type, jobject assetManager) { JNIEnv* env, jclass type, jobject assetManager) {
(void)type; (void)type;
AAssetManager *nativeAssetManager = AAssetManager_fromJava(env, assetManager); AAssetManager* nativeAssetManager = AAssetManager_fromJava(env, assetManager);
gSensorGraph.init(nativeAssetManager); gSensorGraph.init(nativeAssetManager);
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_android_accelerometergraph_AccelerometerGraphJNI_surfaceCreated( Java_com_android_accelerometergraph_AccelerometerGraphJNI_surfaceCreated(
JNIEnv *env, jclass type) { JNIEnv* env, jclass type) {
(void)env; (void)env;
(void)type; (void)type;
gSensorGraph.surfaceCreated(); gSensorGraph.surfaceCreated();
@@ -271,7 +271,7 @@ Java_com_android_accelerometergraph_AccelerometerGraphJNI_surfaceCreated(
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_android_accelerometergraph_AccelerometerGraphJNI_surfaceChanged( Java_com_android_accelerometergraph_AccelerometerGraphJNI_surfaceChanged(
JNIEnv *env, jclass type, jint width, jint height) { JNIEnv* env, jclass type, jint width, jint height) {
(void)env; (void)env;
(void)type; (void)type;
gSensorGraph.surfaceChanged(width, height); gSensorGraph.surfaceChanged(width, height);
@@ -279,7 +279,7 @@ Java_com_android_accelerometergraph_AccelerometerGraphJNI_surfaceChanged(
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_android_accelerometergraph_AccelerometerGraphJNI_drawFrame( Java_com_android_accelerometergraph_AccelerometerGraphJNI_drawFrame(
JNIEnv *env, jclass type) { JNIEnv* env, jclass type) {
(void)env; (void)env;
(void)type; (void)type;
gSensorGraph.update(); gSensorGraph.update();
@@ -287,7 +287,7 @@ Java_com_android_accelerometergraph_AccelerometerGraphJNI_drawFrame(
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_android_accelerometergraph_AccelerometerGraphJNI_pause(JNIEnv *env, Java_com_android_accelerometergraph_AccelerometerGraphJNI_pause(JNIEnv* env,
jclass type) { jclass type) {
(void)env; (void)env;
(void)type; (void)type;
@@ -295,7 +295,7 @@ Java_com_android_accelerometergraph_AccelerometerGraphJNI_pause(JNIEnv *env,
} }
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_android_accelerometergraph_AccelerometerGraphJNI_resume(JNIEnv *env, Java_com_android_accelerometergraph_AccelerometerGraphJNI_resume(JNIEnv* env,
jclass type) { jclass type) {
(void)env; (void)env;
(void)type; (void)type;

View File

@@ -593,8 +593,8 @@ void android_main(android_app* state) {
// If animating, we loop until all events are read, then continue // If animating, we loop until all events are read, then continue
// to draw the next frame of animation. // to draw the next frame of animation.
android_poll_source* source = nullptr; android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr,
(void**)&source); nullptr, (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");
abort(); abort();

View File

@@ -409,8 +409,8 @@ void android_main(android_app* state) {
// If animating, we loop until all events are read, then continue // If animating, we loop until all events are read, then continue
// to draw the next frame of animation. // to draw the next frame of animation.
android_poll_source* source = nullptr; android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr,
(void**)&source); nullptr, (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");
std::abort(); std::abort();

View File

@@ -38,7 +38,7 @@ double PerfMonitor::UpdateTick(double currentTick) {
return ((double)ticksum_ / kNumSamples); return ((double)ticksum_ / kNumSamples);
} }
bool PerfMonitor::Update(float &fFPS) { bool PerfMonitor::Update(float& fFPS) {
struct timeval Time; struct timeval Time;
gettimeofday(&Time, NULL); gettimeofday(&Time, NULL);

View File

@@ -46,7 +46,7 @@ class PerfMonitor {
PerfMonitor(); PerfMonitor();
virtual ~PerfMonitor(); virtual ~PerfMonitor();
bool Update(float &fFPS); bool Update(float& fFPS);
static double GetCurrentTime() { static double GetCurrentTime() {
struct timeval time; struct timeval time;

View File

@@ -42,15 +42,15 @@ enum ORIENTATION {
* *
*/ */
class SensorManager { class SensorManager {
ASensorManager *sensorManager_; ASensorManager* sensorManager_;
const ASensor *accelerometerSensor_; const ASensor* accelerometerSensor_;
ASensorEventQueue *sensorEventQueue_; ASensorEventQueue* sensorEventQueue_;
protected: protected:
public: public:
SensorManager(); SensorManager();
~SensorManager(); ~SensorManager();
void Init(android_app *state); void Init(android_app* state);
void Suspend(); void Suspend();
void Resume(); void Resume();
}; };
@@ -60,6 +60,6 @@ class SensorManager {
* Workaround ASensorManager_getInstance() deprecation false alarm * Workaround ASensorManager_getInstance() deprecation false alarm
* for Android-N and before, when compiling with NDK-r15 * for Android-N and before, when compiling with NDK-r15
*/ */
ASensorManager *AcquireASensorManagerInstance(android_app *app); ASensorManager* AcquireASensorManagerInstance(android_app* app);
} // namespace ndk_helper } // namespace ndk_helper
#endif /* SENSORMANAGER_H_ */ #endif /* SENSORMANAGER_H_ */

View File

@@ -27,8 +27,8 @@ namespace ndk_helper {
#define DEBUG (1) #define DEBUG (1)
bool shader::CompileShader( bool shader::CompileShader(
GLuint *shader, const GLenum type, const char *str_file_name, GLuint* shader, const GLenum type, const char* str_file_name,
const std::map<std::string, std::string> &map_parameters) { const std::map<std::string, std::string>& map_parameters) {
std::vector<uint8_t> data; std::vector<uint8_t> data;
if (!JNIHelper::GetInstance()->ReadFile(str_file_name, &data)) { if (!JNIHelper::GetInstance()->ReadFile(str_file_name, &data)) {
LOGI("Can not open a file:%s", str_file_name); LOGI("Can not open a file:%s", str_file_name);
@@ -70,8 +70,8 @@ bool shader::CompileShader(
return shader::CompileShader(shader, type, v); return shader::CompileShader(shader, type, v);
} }
bool shader::CompileShader(GLuint *shader, const GLenum type, bool shader::CompileShader(GLuint* shader, const GLenum type,
const GLchar *source, const int32_t iSize) { const GLchar* source, const int32_t iSize) {
if (source == NULL || iSize <= 0) return false; if (source == NULL || iSize <= 0) return false;
*shader = glCreateShader(type); *shader = glCreateShader(type);
@@ -84,7 +84,7 @@ bool shader::CompileShader(GLuint *shader, const GLenum type,
GLint logLength; GLint logLength;
glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) { if (logLength > 0) {
GLchar *log = (GLchar *)malloc(logLength); GLchar* log = (GLchar*)malloc(logLength);
glGetShaderInfoLog(*shader, logLength, &logLength, log); glGetShaderInfoLog(*shader, logLength, &logLength, log);
LOGI("Shader compile log:\n%s", log); LOGI("Shader compile log:\n%s", log);
free(log); free(log);
@@ -101,17 +101,17 @@ bool shader::CompileShader(GLuint *shader, const GLenum type,
return true; return true;
} }
bool shader::CompileShader(GLuint *shader, const GLenum type, bool shader::CompileShader(GLuint* shader, const GLenum type,
std::vector<uint8_t> &data) { std::vector<uint8_t>& data) {
if (!data.size()) return false; if (!data.size()) return false;
const GLchar *source = (GLchar *)&data[0]; const GLchar* source = (GLchar*)&data[0];
int32_t iSize = data.size(); int32_t iSize = data.size();
return shader::CompileShader(shader, type, source, iSize); return shader::CompileShader(shader, type, source, iSize);
} }
bool shader::CompileShader(GLuint *shader, const GLenum type, bool shader::CompileShader(GLuint* shader, const GLenum type,
const char *strFileName) { const char* strFileName) {
std::vector<uint8_t> data; std::vector<uint8_t> data;
bool b = JNIHelper::GetInstance()->ReadFile(strFileName, &data); bool b = JNIHelper::GetInstance()->ReadFile(strFileName, &data);
if (!b) { if (!b) {
@@ -131,7 +131,7 @@ bool shader::LinkProgram(const GLuint prog) {
GLint logLength; GLint logLength;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) { if (logLength > 0) {
GLchar *log = (GLchar *)malloc(logLength); GLchar* log = (GLchar*)malloc(logLength);
glGetProgramInfoLog(prog, logLength, &logLength, log); glGetProgramInfoLog(prog, logLength, &logLength, log);
LOGI("Program link log:\n%s", log); LOGI("Program link log:\n%s", log);
free(log); free(log);
@@ -153,7 +153,7 @@ bool shader::ValidateProgram(const GLuint prog) {
glValidateProgram(prog); glValidateProgram(prog);
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0) { if (logLength > 0) {
GLchar *log = (GLchar *)malloc(logLength); GLchar* log = (GLchar*)malloc(logLength);
glGetProgramInfoLog(prog, logLength, &logLength, log); glGetProgramInfoLog(prog, logLength, &logLength, log);
LOGI("Program validate log:\n%s", log); LOGI("Program validate log:\n%s", log);
free(log); free(log);

View File

@@ -48,8 +48,8 @@ namespace shader {
* return: true if a shader compilation succeeded, false if it failed * return: true if a shader compilation succeeded, false if it failed
* *
*/ */
bool CompileShader(GLuint *shader, const GLenum type, bool CompileShader(GLuint* shader, const GLenum type,
std::vector<uint8_t> &data); std::vector<uint8_t>& data);
/****************************************************************** /******************************************************************
* CompileShader() with buffer * CompileShader() with buffer
@@ -62,7 +62,7 @@ bool CompileShader(GLuint *shader, const GLenum type,
* return: true if a shader compilation succeeded, false if it failed * return: true if a shader compilation succeeded, false if it failed
* *
*/ */
bool CompileShader(GLuint *shader, const GLenum type, const GLchar *source, bool CompileShader(GLuint* shader, const GLenum type, const GLchar* source,
const int32_t iSize); const int32_t iSize);
/****************************************************************** /******************************************************************
@@ -75,7 +75,7 @@ bool CompileShader(GLuint *shader, const GLenum type, const GLchar *source,
* return: true if a shader compilation succeeded, false if it failed * return: true if a shader compilation succeeded, false if it failed
* *
*/ */
bool CompileShader(GLuint *shader, const GLenum type, const char *strFileName); bool CompileShader(GLuint* shader, const GLenum type, const char* strFileName);
/****************************************************************** /******************************************************************
* CompileShader() with std::map helps patching on a shader on the fly. * CompileShader() with std::map helps patching on a shader on the fly.
@@ -90,8 +90,8 @@ bool CompileShader(GLuint *shader, const GLenum type, const char *strFileName);
* return: true if a shader compilation succeeded, false if it failed * return: true if a shader compilation succeeded, false if it failed
* *
*/ */
bool CompileShader(GLuint *shader, const GLenum type, const char *str_file_name, bool CompileShader(GLuint* shader, const GLenum type, const char* str_file_name,
const std::map<std::string, std::string> &map_parameters); const std::map<std::string, std::string>& map_parameters);
/****************************************************************** /******************************************************************
* LinkProgram() * LinkProgram()

View File

@@ -409,8 +409,8 @@ void android_main(android_app* state) {
// If animating, we loop until all events are read, then continue // If animating, we loop until all events are read, then continue
// to draw the next frame of animation. // to draw the next frame of animation.
android_poll_source* source = nullptr; android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr,
(void**)&source); nullptr, (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");

View File

@@ -421,8 +421,8 @@ void android_main(android_app* state) {
// If animating, we loop until all events are read, then continue // If animating, we loop until all events are read, then continue
// to draw the next frame of animation. // to draw the next frame of animation.
android_poll_source* source = nullptr; android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr,
(void**)&source); nullptr, (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");
std::abort(); std::abort();

View File

@@ -409,17 +409,17 @@ void android_main(android_app* state) {
// If animating, we loop until all events are read, then continue // If animating, we loop until all events are read, then continue
// to draw the next frame of animation. // to draw the next frame of animation.
android_poll_source* source = nullptr; android_poll_source* source = nullptr;
auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr, nullptr, auto result = ALooper_pollOnce(g_engine.IsReady() ? 0 : -1, nullptr,
(void**)&source); nullptr, (void**)&source);
if (result == ALOOPER_POLL_ERROR) { if (result == ALOOPER_POLL_ERROR) {
LOGE("ALooper_pollOnce returned an error"); LOGE("ALooper_pollOnce returned an error");
std::abort(); std::abort();
} }
// Process this event. // Process this event.
if (source != NULL) source->process(state, source); if (source != NULL) source->process(state, source);
g_engine.ProcessSensors(result); g_engine.ProcessSensors(result);
if (g_engine.IsReady()) { if (g_engine.IsReady()) {
// Drawing is throttled to the screen update rate, so there // Drawing is throttled to the screen update rate, so there

View File

@@ -54,8 +54,8 @@ Texture::Texture(std::vector<std::string>& asset_paths,
fileBits.clear(); fileBits.clear();
AssetReadFile(asset_manager, asset_paths[i], fileBits); AssetReadFile(asset_manager, asset_paths[i], fileBits);
// tga/bmp asset_paths are saved as vertical mirror images ( at least more than // tga/bmp asset_paths are saved as vertical mirror images ( at least more
// half ). // than half ).
stbi_set_flip_vertically_on_load(1); stbi_set_flip_vertically_on_load(1);
uint8_t* imageBits = uint8_t* imageBits =
@@ -100,7 +100,7 @@ bool Texture::Activate(void) {
Cubemap just used one sampler at unit 0 with "samplerObj" as its name. Cubemap just used one sampler at unit 0 with "samplerObj" as its name.
*/ */
void Texture::GetActiveSamplerInfo(std::vector<std::string>& names, void Texture::GetActiveSamplerInfo(std::vector<std::string>& names,
std::vector<GLint>& units) { std::vector<GLint>& units) {
names.clear(); names.clear();
names.push_back(std::string("samplerObj")); names.push_back(std::string("samplerObj"));
units.clear(); units.clear();