I am learning to make QRCode in esp32-2432s028 - c++

I am learning to make QRCode in esp32-2432s028 (this pictura) from https://www.youtube.com/watch?v=Ss3zBO-V9kI I have problem.
From code
/*
QR Code Maker (ESP32+LVGL8)
For More Information: https://youtu.be/Ss3zBO-V9kI
Created by Eric N. (ThatProject)
*/
/////////////////////////////////////////////////////////////////
#include <lvgl.h>
#include "MyDisplay.h"
static const uint32_t screenWidth = 320;
static const uint32_t screenHeight = 480;
static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[ screenWidth * 10 ];
lv_obj_t * mainScreen;
lv_obj_t * titleImage;
lv_obj_t * qrCode;
LV_IMG_DECLARE(ui_logo_img_obj);
void my_disp_flush( lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p )
{
uint32_t w = ( area->x2 - area->x1 + 1 );
uint32_t h = ( area->y2 - area->y1 + 1 );
tft.startWrite();
tft.setAddrWindow( area->x1, area->y1, w, h );
tft.writePixels((lgfx::rgb565_t *)&color_p->full, w * h);
tft.endWrite();
lv_disp_flush_ready( disp );
}
void my_touchpad_read( lv_indev_drv_t * indev_driver, lv_indev_data_t * data )
{
if (ts.touched()) {
data->state = LV_INDEV_STATE_PR;
TS_Point p = ts.getPoint();
data->point.x = p.x;
data->point.y = p.y;
} else {
data->state = LV_INDEV_STATE_REL;
}
}
void setup()
{
Serial.begin(115200);
tft.begin();
tft.setRotation(0);
tft.setBrightness(255);
if (!ts.begin(40, SDA_FT6236, SCL_FT6236)) {
Serial.println("Unable to start the capacitive touch Screen.");
}
lv_init();
lv_disp_draw_buf_init( &draw_buf, buf, NULL, screenWidth * 10 );
static lv_disp_drv_t disp_drv;
lv_disp_drv_init(&disp_drv);
disp_drv.hor_res = screenWidth;
disp_drv.ver_res = screenHeight;
disp_drv.flush_cb = my_disp_flush;
disp_drv.draw_buf = &draw_buf;
lv_disp_drv_register(&disp_drv);
static lv_indev_drv_t indev_drv;
lv_indev_drv_init(&indev_drv);
indev_drv.type = LV_INDEV_TYPE_POINTER;
indev_drv.read_cb = my_touchpad_read;
lv_indev_drv_register(&indev_drv);
ui_init();
}
void loop() {
lv_timer_handler();
delay( 5 );
}
void ui_init() {
ui_background();
ui_dynamic_obj();
lv_disp_load_scr(mainScreen);
}
void ui_background() {
mainScreen = lv_obj_create(NULL);
lv_obj_clear_flag(mainScreen, LV_OBJ_FLAG_SCROLLABLE);
titleImage = lv_img_create(mainScreen);
lv_img_set_src(titleImage, &ui_logo_img_obj);
lv_obj_set_size(titleImage, 320, 117);
lv_obj_set_pos(titleImage, 0, 0);
lv_obj_set_align(titleImage, LV_ALIGN_TOP_MID);
lv_obj_add_flag(titleImage, LV_OBJ_FLAG_ADV_HITTEST);
lv_obj_clear_flag(titleImage, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t * titleLabel = lv_label_create(mainScreen);
lv_obj_set_pos(titleLabel, 0, 120);
lv_obj_set_align(titleLabel, LV_ALIGN_TOP_MID);
lv_label_set_text(titleLabel, "QR Code Maker");
lv_obj_clear_flag(titleLabel, LV_OBJ_FLAG_CLICKABLE);
lv_obj_set_style_text_font(titleLabel, &lv_font_montserrat_34, LV_PART_MAIN | LV_STATE_DEFAULT);
}
static void ta_event_cb(lv_event_t * e) {
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * ta = lv_event_get_target(e);
lv_obj_t * kb = (lv_obj_t*)lv_event_get_user_data(e);
if (code == LV_EVENT_READY) {
lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
const char * text = lv_textarea_get_text(ta);
if (strlen(text) == 0) return;
lv_qrcode_update(qrCode, text, strlen(text));
lv_obj_clear_flag(qrCode, LV_OBJ_FLAG_HIDDEN);
}
if (code == LV_EVENT_CLICKED || code == LV_EVENT_FOCUSED) {
lv_keyboard_set_textarea(kb, ta);
lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(qrCode, LV_OBJ_FLAG_HIDDEN);
}
if (code == LV_EVENT_DEFOCUSED) {
lv_keyboard_set_textarea(kb, NULL);
lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
}
}
void ui_dynamic_obj(void) {
lv_obj_t * kb = lv_keyboard_create(mainScreen);
lv_obj_t * ta = lv_textarea_create(mainScreen);
lv_obj_align(ta, LV_ALIGN_CENTER, 0, -40);
lv_obj_add_event_cb(ta, ta_event_cb, LV_EVENT_ALL, kb);
lv_obj_set_size(ta, screenWidth - 40, 60);
lv_keyboard_set_textarea(kb, ta);
qrCode = lv_qrcode_create(mainScreen, 200, lv_color_hex3(0x000), lv_color_hex3(0xeef));
lv_obj_set_pos(qrCode, 0, -20);
lv_obj_set_align(qrCode, LV_ALIGN_BOTTOM_MID);
lv_obj_add_flag(qrCode, LV_OBJ_FLAG_HIDDEN);
}
I run in arduino ide 2.0.1
It shown error is:
C:\Users\Supakee\Documents\Arduino\QRCODE\QRCODE.ino: In function 'void ui_dynamic_obj()':
C:\Users\Supakee\Documents\Arduino\QRCODE\QRCODE.ino:141:88: error: too many arguments to function 'lv_obj_t* lv_qrcode_create(lv_obj_t*)'
qrCode = lv_qrcode_create(mainScreen, 200, lv_color_hex3(0x000), lv_color_hex3(0xeef));
^
In file included from c:\users\supakee\documents\arduino\libraries\lvgl-d17450a55fbd8603e57b64d23feb36a63832b195\lvgl.h:91,
from c:\Users\Supakee\Documents\Arduino\libraries\lvgl-d17450a55fbd8603e57b64d23feb36a63832b195\src/lvgl.h:17,
from C:\Users\Supakee\Documents\Arduino\QRCODE\QRCODE.ino:7:
c:\users\supakee\documents\arduino\libraries\lvgl-d17450a55fbd8603e57b64d23feb36a63832b195\src/libs/qrcode/lv_qrcode.h:45:12: note: declared here
lv_obj_t * lv_qrcode_create(lv_obj_t * parent);
^~~~~~~~~~~~~~~~
Multiple libraries were found for "lvgl.h"
Used: C:\Users\Supakee\Documents\Arduino\libraries\lvgl-d17450a55fbd8603e57b64d23feb36a63832b195
Not used: C:\Users\Supakee\Documents\Arduino\libraries\src
exit status 1
Compilation error: too many arguments to function 'lv_obj_t* lv_qrcode_create(lv_obj_t*)'
I tried to follow instruction in LVGL Document.
I want to make this esp32-2432s028 to display QR code so how can i do it?
I use library from https://github.com/lvgl/lvgl/tree/6948eee9b12e13ea7db9287b96385b05a8a6cc9a
I use code from https://github.com/0015/ThatProject/tree/master/ESP32_LVGL/LVGL8/4_QR_Code_Maker

The compilation error:
Compilation error: too many arguments to function 'lv_obj_t* lv_qrcode_create(lv_obj_t*)'
Suggests that you should only send a single argument to the function
qrCode = lv_qrcode_create(mainScreen, 200, lv_color_hex3(0x000), lv_color_hex3(0xeef));
Does the documentation you have read differ from the implementation you are using?

Related

Keras custom layer with CNTK backend (CRF as RNN)

I am attempting to duplicate the CRF as RNN which has been implemented in Keras but uses TensorFlow as a backend (https://github.com/sadeepj/crfasrnn_keras). The Keras front-end is fine, but some of the backend code is written as a TensorFlow custom op. I am trying to duplicate this in CNTK, but I have a few questions.
import cntk as C
from cntk import ops
import copy
import numpy as np
C.device.try_set_default_device(C.device.cpu())
ops.register_native_user_function('HighDimFilterOp', 'Cntk.HighDimFilter-' + C.__version__.rstrip('+'), 'CreateHighDimFilter')
def high_dim_filter(image=None, rgb=None, **kwargs):
inputs = [list(image), list(rgb)];
layer_config = copy.deepcopy(kwargs)
ops.native_user_function('HighDimFilterOp', inputs, layer_config, 'high_dim_filter')
This code is the Python call to my user C++ function. The C++ interface is as follows:
#include "HighDimFilter.h"
using namespace CNTK;
extern "C"
#ifdef _WIN32
__declspec(dllexport)
#endif
Function* CreateHighDimFilter(const Variable* operands, size_t /*numOperands*/, const Dictionary* attributes, const wchar_t* name)
{
printf("Creating HighDimFilter\n");
return new HighDimFilter({operands[0], operands[1]}, *attributes, name);
}
and the custom function itself is defined as:
#pragma once
#include "CNTKLibrary.h"
#include "modified_permutohedral.h"
using namespace CNTK;
class HighDimFilter final : public Function
{
bool _bilateral;
float _theta_alpha;
float _theta_beta;
float _theta_gamma;
enum Input : uint32_t
{
SCORES,
IM_INFO
};
public:
HighDimFilter(const std::vector<Variable>& inputs, const Dictionary& attributes, const std::wstring& name = L"HighDimFilter")
: Function(inputs, attributes, name)
{
if (attributes.Contains(L"bilateral"))
_bilateral = attributes[L"bilateral"].Value<bool>();
if (_bilateral == false)
{
if (attributes.Contains(L"theta_gamma"))
_theta_gamma = static_cast<float>(attributes[L"theta_gamma"].Value<double>());
}
else
{
if (attributes.Contains(L"theta_alpha"))
_theta_alpha = static_cast<float>(attributes[L"theta_alpha"].Value<double>());
if (attributes.Contains(L"theta_beta"))
_theta_beta = static_cast<float>(attributes[L"theta_beta"].Value<double>());
}
}
private:
void _compute_spatial_kernel(NDArrayViewPtr& Tensor, const float theta_gamma)
{
auto output_kernel = Tensor->WritableDataBuffer<float>();
auto outputShape = Tensor->Shape();
//auto channels = outputShape[0];
auto height = outputShape[1];
auto width = outputShape[2];
const auto num_pixels = width * height;
for (int p = 0; p < num_pixels; ++p)
{
output_kernel[2 * p] = static_cast<float>(p % width) / theta_gamma;
output_kernel[2 * p + 1] = static_cast<float>(p / width) / theta_gamma;
}
}
void _compute_bilateral_kernel(NDArrayViewPtr& Tensor, const NDArrayViewPtr& Image,
const float theta_alpha, const float theta_beta)
{
auto output_kernel = Tensor->WritableDataBuffer<float>();
auto rgb = Image->DataBuffer<float>();
auto outputShape = Tensor->Shape();
//auto channels = outputShape[0];
auto height = outputShape[1];
auto width = outputShape[2];
const auto num_pixels = height * width;
for (int p = 0; p < num_pixels; ++p)
{
// Spatial terms
output_kernel[5 * p] = static_cast<float>(p % width) / theta_alpha;
output_kernel[5 * p + 1] = static_cast<float>(p / width) / theta_alpha;
// Color terms
output_kernel[5 * p + 2] = static_cast<float>(rgb[p] / theta_beta);
output_kernel[5 * p + 3] = static_cast<float>(rgb[num_pixels + p] / theta_beta);
output_kernel[5 * p + 4] = static_cast<float>(rgb[2 * num_pixels + p] / theta_beta);
}
}
BackPropStatePtr Forward(const std::vector<ValuePtr>& inputValues,
std::unordered_map<Variable, ValuePtr>& outputs,
const DeviceDescriptor& computeDevice,
const std::unordered_set<Variable>& /*outputsToRetainBackwardStateFor */) override
{
#if 0
auto scoresShape = inputValues[Input::SCORES]->Shape();
auto channels = scoresShape[0];
auto height = scoresShape[1];
auto width = scoresShape[2];
const auto num_pixels = width * height;
auto &outputValue = outputs[this->Output()];
if (outputValue == nullptr)
{
outputValue = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(DataType::Float, scoresShape, computeDevice));
}
if (computeDevice.Type() != DeviceKind::CPU)
throw std::runtime_error("HighDimFilter: only CPU evaluation is supported at the moment.");
ModifiedPermutohedral mp;
if (_bilateral)
{
auto &kernel_vals = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(DataType::Float, NDShape({5, height, width}), computeDevice));
//float* kernel_vals = new float[5 * num_pixels];
_compute_bilateral_kernel(kernel_vals->Data(), inputValues[Input::IM_INFO]->Data(),
_theta_alpha, _theta_beta);
mp.init(kernel_vals->Data(), 5, num_pixels);
mp.compute(outputValue->Data(), inputValues[Input::SCORES]->Data(), false);
}
else
{
auto &kernel_vals = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(DataType::Float, NDShape({2, height, width}), computeDevice));
_compute_spatial_kernel(kernel_vals->Data(), _theta_gamma);
mp.init(kernel_vals->Data(), 2, num_pixels);
mp.compute(outputValue->Data(), inputValues[Input::SCORES]->Data(), channels, false);
}
return MakeSharedObject<BackPropState>(this->shared_from_this(), computeDevice, std::unordered_map<Variable, ValuePtr>({ {Inputs()[Input::IM_INFO], inputValues[Input::IM_INFO]} }));
#else
return nullptr;
#endif
}
void Backward(const BackPropStatePtr& state,
const std::unordered_map<Variable, ValuePtr>& rootGradientValues,
std::unordered_map<Variable, ValuePtr>& backPropagatedGradientValuesForInputs) override
{
#if 0
auto gradOutputVariable = Inputs()[Input::SCORES];
auto inputVariable = Inputs()[Input::IM_INFO];
auto &gradValue = backPropagatedGradientValuesForInputs[gradOutputVariable];
if (gradValue == nullptr)
gradValue = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(DataType::Float, gradOutputVariable.Shape(), state->Device()));
auto imageData = state->SavedForwardPropValues().at(inputVariable)->Data();
auto imageShape = imageData->Shape();
auto channels = imageShape[0];
auto height = imageShape[1];
auto width = imageShape[2];
const auto num_pixels = width * height;
if (state->Device().Type() != DeviceKind::CPU)
throw std::runtime_error("HighDimFilter: only CPU evaluation is supported at the moment.");
auto rootGradientData = rootGradientValues.at(this->Output())->Data();
ModifiedPermutohedral mp;
if (_bilateral)
{
auto &kernel_vals = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(DataType::Float, NDShape({5, height, width}), state->Device()));
//float* kernel_vals = new float[5 * num_pixels];
_compute_bilateral_kernel(kernel_vals->Data(), imageData,
_theta_alpha, _theta_beta);
mp.init(kernel_vals->Data(), 5, num_pixels);
mp.compute(gradValue->Data(), rootGradientData, true);
}
else
{
auto &kernel_vals = MakeSharedObject<Value>(MakeSharedObject<NDArrayView>(DataType::Float, NDShape({2, height, width}), state->Device()));
_compute_spatial_kernel(kernel_vals->Data(), _theta_gamma);
mp.init(kernel_vals->Data(), 2, num_pixels);
mp.compute(gradValue->Data(), rootGradientData, channels, true);
}
#endif
return;
}
const std::wstring& OpName() const override
{
static const std::wstring opName = L"HighDimFilterOp";
return opName;
}
size_t CurrentVersion() const override
{
NOT_IMPLEMENTED;
}
void InferOutputs(std::vector<Variable>& /*outputs */) override
{
NOT_IMPLEMENTED;
}
FunctionPtr Clone(const std::vector<Variable>& /*clonedInputs */) override
{
return nullptr;
}
};
My python call looks like:
bilateral_high_dim_filter = custom_module.high_dim_filter(image=all_ones_flat,
rgb=rgb_flat,
bilateral=True,
theta_alpha=self.theta_alpha,
theta_beta=self.theta_beta)
high_dim_filter = custom_module.high_dim_filter(image=all_ones_flat,
rgb=rgb_flat,
bilateral=False,
theta_gamma=self.theta_gamma)
The questions are as follows: 1) What are the "operands" passed in to the native_user_function on initialization? Are these only passed on initialization (are they intended to be weight and bias initialization)? How are the input operands used in the "Function" construction initializer? If I set these to "None" in Python, the code crashes.
2) How do you forward propagate the filter? Just call "forward()"? What about the required arguments to forward propagate?
3) Is there a numerical gradient calculation in CNTK similar to TensorFlow to check the gradient?

Allegro 5 Play Multiple Samples at Once

I've come across an issue with playing samples Allegro 5. When I play a sample, I can't play that sample again until it's finished playing. Sometimes it will also not play the sample if another, different, sample is playing.
Anyway to get around this?
I play audio with a "Sound" class, which only has a play function. The rest are constuctors and member vars, all of which are used in the play function.
void Sound::play()
{
al_play_sample(
pSample, // ALLEGRO_SAMPLE
mGain, // float
mPan, // float
mSpeed, // float
getPlaymode(mPlaymode), // I use my own non-AL playmode enums. This is a private function that returns the AL version.
NULL); // ALLEGRO_SAMPLE_ID
}
The whole class:
Sound.h
class ContentManager;
enum Playmode
{
BiDir,
Loop,
Once,
StreamOnce,
StreamOneDir
};
class Sound : public Trackable
{
private:
/* Variables
* * * * * * * * * * * * */
ALLEGRO_SAMPLE* pSample;
float
mGain,
mPan,
mSpeed;
Playmode mPlaymode;
std::string
mAssetPath,
mAssetName;
/* Private Functions
* * * * * * * * * * * * */
ALLEGRO_PLAYMODE getPlaymode(Playmode playmode)
{
switch (playmode)
{
case BiDir:
return ALLEGRO_PLAYMODE::ALLEGRO_PLAYMODE_BIDIR;
case Loop:
return ALLEGRO_PLAYMODE::ALLEGRO_PLAYMODE_LOOP;
case Once:
return ALLEGRO_PLAYMODE::ALLEGRO_PLAYMODE_ONCE;
case StreamOnce:
return ALLEGRO_PLAYMODE::_ALLEGRO_PLAYMODE_STREAM_ONCE;
case StreamOneDir:
return ALLEGRO_PLAYMODE::_ALLEGRO_PLAYMODE_STREAM_ONEDIR;
// Default to once
default:
return ALLEGRO_PLAYMODE::ALLEGRO_PLAYMODE_ONCE;
}
}
public:
/* Constructors/Destructor
* * * * * * * * * * * * */
Sound();
Sound(
// assetPath, assetName, gain, pan, speed, playmode
std::string assetPath,
std::string assetName,
float gain = 1.0f,
float pan = 0.0f,
float speed = 1.0f,
Playmode playmode = Once);
Sound(const Sound& other);
~Sound();
friend class ContentManager; // My content system.
void play();
};
Sound.cpp
#include "Sound.h"
/* Constructors/Destructor
* * * * * * * * * * * * */
Sound::Sound()
{
this->mAssetPath = "";
this->mAssetName = "";
this->mGain = 1.0f;
this->mPan = 0.0f;
this->mSpeed = 1.0f;
this->mPlaymode = Once;
this->pSample = NULL;
}
Sound::Sound(std::string assetPath, std::string assetName, float gain, float pan, float speed, Playmode playmode)
{
this->mAssetPath = assetPath;
this->mAssetName = assetName;
this->mGain = gain;
this->mPan = pan;
this->mSpeed = speed;
this->mPlaymode = playmode;
this->pSample = al_load_sample((assetPath + assetName).c_str());
}
Sound::Sound(const Sound& other)
{
this->mAssetPath = other.mAssetPath;
this->mAssetName = other.mAssetName;
this->mGain = other.mGain;
this->mPan = other.mPan;
this->mSpeed = other.mSpeed;
this->mPlaymode = other.mPlaymode;
this->pSample = al_load_sample((mAssetPath + mAssetName).c_str());
}
Sound::~Sound()
{
al_destroy_sample(pSample);
}
void Sound::play()
{
al_play_sample(
pSample,
mGain,
mPan,
mSpeed,
getPlaymode(mPlaymode),
NULL);
}
I call the play function through the rest of my system, which would look something like this:
// Game->ContentManager->Sound->play()
Game::instance()->content()->getSound("somesound.wav")->play();
Content manager contains maps of my assets.
This is part of a larger project I'm working on for a class, but no, this part isn't homework. My professor disallowed us from having any public/top level AL codes (e.g. no public AL returns, etc).
Let me know if I need to clarify anything. Any help is always appreciated.
I might be wrong, but it sounds like you have to reserve more samples using al_reserve_samples(number_of_samples);
Based off of ppsz's answer, I did some digging and did the following based on what I found.
int numSamples = /*Some int*/
int reservedSamples = 0;
int i = (numSamples >= 1 ? numSamples : 1);
bool success = false;
do
{
success = al_reserve_samples(i);
i -= 1;
}
while (success == false || i > 0);
Source

How to resize an image from an rgb buffer using c++

I have an (char*)RGB buffer that has the data of actual image. Let's say that the actual image resolution is 720x576. Now I want to resize it to a resolution , say 120x90.
How can I do this using https://code.google.com/p/jpeg-compressor/ or libjpeg ?
Note: can use any other library, but should work in linux.
Edited: Video decoder decodes a frame in YUV, which I convert it into RGB. All these happen in a buffer.
I need to resize the RGB buffer to make a thumbnail out of it with variable size.
Thanks for the help in advance
I did the following to achieve my goal:
#define TN_WIDTH 240
#define TN_HEIGHT 180
#include "jpegcompressor/jpge.h"
#include "jpegcompressor/jpgd.h"
#include <ippi.h>
bool createThumnailJpeg(const uint8* pSrc, int srcwidth, int srcheight)
{
int req_comps = 3;
jpge::params params;
params.m_quality = 50;
params.m_subsampling = jpge::H2V2;
params.m_two_pass_flag = false;
FILE *fpJPEGTN = fopen("Resource\\jpegcompressor.jpeg","wb");
int dstWidth = TN_WIDTH;
int dstHeight = TN_HEIGHT;
int uiDstBufferSize = dstWidth * dstHeight * 3;
uint8 *pDstRGBBuffer = new uint8[uiDstBufferSize];
uint8 *pJPEGTNBuffer = new uint8[uiDstBufferSize];
int uiSrcBufferSize = srcwidth * srcheight * 3;
IppiSize srcSize = {srcwidth , srcheight};
IppiRect srcROI = {0, 0, srcwidth, srcheight};
IppiSize dstROISize = {dstWidth, dstHeight};
double xfactor = (double) dstWidth / srcwidth;
double yfactor = (double) dstHeight / srcheight;
IppStatus status = ippiResize_8u_C3R(pSrc, srcSize, srcwidth*3, srcROI,
pDstRGBBuffer, dstWidth*3, dstROISize, xfactor, yfactor, 1);
if (!jpge::compress_image_to_jpeg_file_in_memory(pJPEGTNBuffer, uiDstBufferSize, dstWidth, dstHeight, req_comps, pDstRGBBuffer, params))
{
cout << "failed!";
delete[] pDstRGBBuffer;
delete [] pJPEGTNBuffer;
return false;
}
if (fpJPEGTN)
{
fwrite(pJPEGTNBuffer, uiDstBufferSize, 1, fpJPEGTN);
fclose(fpJPEGTN);
}
delete [] pDstRGBBuffer;
delete [] pJPEGTNBuffer;
return true;
}

Convert simple C++ code to Google docs spread sheet OR Excel

I've simple C++ code need to convert it to Google docs spreadsheet but unfortunately it didn't work because of brackets issue... May you please help me to fix Google doc cell format?
C++ code
#ifndef DEMMURAGE_H
#define DEMMURAGE_H
#include <QtCore>
class Demmurage : public QObject
{
Q_OBJECT
public:
Demmurage(QDate vesselArrival,
QDate containerDelivery,
int containerSize,
int freeDuration = 10,
int stageOneDays = 10,
int stageOne40Dem = 15,
int stageTwo40Dem = 25,
int stageOne20Dem = 10,
int stageTwo20Dem = 15,
double dollarToDynar = 1.4)
{
_arrival = vesselArrival;
_delivery = containerDelivery;
_containerSize = containerSize;
_freeDuration = freeDuration;
_stageOneDays = stageOneDays;
_stageOne40Dem = stageOne40Dem;
_stageTwo40Dem = stageTwo40Dem;
_stageOne20Dem = stageOne20Dem;
_stageTwo20Dem = stageTwo20Dem;
_dollarToDynar = dollarToDynar;
_demurrage = 0;
int duration = _arrival.daysTo(_delivery) - _freeDuration;
if (duration > 0) {
if (duration - _stageOneDays <= 0) {
if (containerSize == 40)
_demurrage = duration * _stageOne40Dem * _dollarToDynar;
else
_demurrage = duration * _stageOne20Dem * _dollarToDynar;
} else {
if (containerSize == 40)
_demurrage = (_stageOneDays * _stageOne40Dem * _dollarToDynar) + ( (duration - _stageOneDays) * _stageTwo40Dem * _dollarToDynar);
else
_demurrage = (_stageOneDays * _stageOne20Dem * _dollarToDynar) + ( (duration - _stageOneDays) * _stageTwo20Dem * _dollarToDynar);
}
}
}
double demmurage()
{
return _demurrage;
}
virtual ~Demmurage() {}
private:
double _demurrage;
int _freeDuration;
int _stageOneDays;
int _stageOne40Dem;
int _stageTwo40Dem;
int _stageOne20Dem;
int _stageTwo20Dem;
double _dollarToDynar;
};
#endif // DEMMURAGE_H
Cell of Google docs spreadsheet:
=if( ((L84-I84-10) > 0), ((if ((L84-I84-10) - 10 <= 0), (if( (F84==40), (L84-I84-10)*15*1.4, (L84-I84-10)*10*1.4 )), (if( (F84==40), (10*15*1.4)+(((L84-I84-10)-10)*25*1.4), (10*10*1.4)+(((L84-I84-10)-10)*15*1.4) )))), 0)
I found the error... it happen because of (IF and 40==
The correct format is:
=if((L84-I84-10)>0,if((L84-I84-10)-10<=0,if(F84=40,(L84-I84-10)*15*1.4,(L84-I84-10)*10*1.4),if(F84=40,(10*15*1.4)+(((L84-I84-10)-10)*25*1.4),(10*10*1.4)+(((L84-I84-10)-10)*15*1.4))),0)

LevelHelper Car Design Revolute joint anchor issue

I am trying to replicate the effect from this link Side way car movement I am using levelHelper to design the car. but unable to replicate the effect. I Think i am doing mistake in revolute joint. Here is the code i am trying.
#include "GamePlayScene.h"
#include "LevelManager.h"
#include "Constants.h"
#include "iostream"
void GamePlayScene::InitPhysics()
{
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
m_pB2World = new b2World(gravity);
m_pB2World->SetAllowSleeping(true);
m_pB2World->SetContinuousPhysics(true);
m_pDebugDraw = new GLESDebugDraw( LevelHelperLoader::pixelsToMeterRatio() );
PTM_RATIO = LevelHelperLoader::pixelsToMeterRatio();
m_pB2World->SetDebugDraw(m_pDebugDraw);
m_pLoader= new LevelHelperLoader("track7.plhs");
m_pLoader->addObjectsToWorld(m_pB2World,this);
m_pB2World->ClearForces();
//m_pB2World->DestroyJoint()
LHSprite * carBody = m_pLoader->spriteWithUniqueName("CarBody");
m_pCarBody = carBody->getBody();
m_pCarBody->GetFixtureList()->SetDensity(CAR_BODY_DENSITY);
m_pCarBody->ResetMassData();
m_pCarBody->GetFixtureList()->SetFriction(CAR_BODY_FRICTION);
m_pCarBody->GetFixtureList()->SetRestitution(CAR_BODY_RESTITUTION);
LHSprite * chasis = m_pLoader->spriteWithUniqueName("Chasis");
m_pChasis = chasis->getBody();
m_pChasis->GetFixtureList()->SetDensity(CHASIS_DENSITY);
m_pChasis->ResetMassData();
m_pChasis->GetFixtureList()->SetFriction(CHASIS_FRICTION);
m_pChasis->GetFixtureList()->SetRestitution(CHASIS_RESTITUTION);
//m_pChasis->remove
LHSprite * frontWheel = m_pLoader->spriteWithUniqueName("FrontWheel");
m_pFrontWheel = frontWheel->getBody();
m_pFrontWheel->GetFixtureList()->SetDensity(FRONT_WHEEL_DENSITY);
m_pFrontWheel->ResetMassData();
m_pFrontWheel->GetFixtureList()->SetFriction(FRONT_WHEEL_FRICTION);
m_pFrontWheel->GetFixtureList()->SetRestitution(FRONT_WHEEL_RESTITUTION);
LHSprite * rearWheel = m_pLoader->spriteWithUniqueName("RearWheel");
m_pRearWheel = rearWheel->getBody();
m_pRearWheel->GetFixtureList()->SetDensity(REAR_WHEEL_DENSITY);
m_pRearWheel->ResetMassData();
m_pRearWheel->GetFixtureList()->SetFriction(REAR_WHEEL_FRICTION);
m_pRearWheel->GetFixtureList()->SetRestitution(REAR_WHEEL_RESTITUTION);
LHSprite * frontDamper = m_pLoader->spriteWithUniqueName("FrontDamper");
m_pFrontDamper = frontDamper->getBody();
m_pFrontDamper->GetFixtureList()->SetDensity(FRONT_DAMPER_DENSITY);
m_pFrontDamper->ResetMassData();
m_pFrontDamper->GetFixtureList()->SetFriction(FRONT_DAMPER_FRICTION);
m_pFrontDamper->GetFixtureList()->SetRestitution(FRONT_DAMPER_RESTITUTION);
LHSprite * rearDamper = m_pLoader->spriteWithUniqueName("RearDamper");
m_pRearDamper = rearDamper->getBody();
m_pRearDamper->GetFixtureList()->SetDensity(REAR_DAMPER_DENSITY);
m_pRearDamper->ResetMassData();
m_pRearDamper->GetFixtureList()->SetFriction(REAR_DAMPER_FRICTION);
m_pRearDamper->GetFixtureList()->SetRestitution(REAR_DAMPER_RESTITUTION);
b2PolygonShape * shape = (b2PolygonShape *)m_pChasis->GetFixtureList()->GetShape();
//shape->SetAsBox(
LHJoint * frontPrismJoint = frontDamper->jointWithUniqueName("FrontDamperChasis");
LH_JOINT_TYPE type2 = frontPrismJoint->getType();
if(type2 == LH_PRISMATIC_JOINT)
{
//m_pFrontPrismJoint = (b2PrismaticJoint *)frontPrismJoint;
//b2PrismaticJointDef prismJointDef;
frontPrismJointDef = new b2PrismaticJointDef();
//b2Vec2 anchor = m_pFrontDamper->GetWorldCenter() - m_pChasis->GetWorldCenter();
frontPrismJointDef->Initialize(m_pChasis,m_pFrontDamper, m_pFrontDamper->GetWorldCenter(), b2Vec2(0, 1));
frontPrismJointDef->enableLimit = FRONT_PRISM_JOINT_ENABLE_LIMIT;
frontPrismJointDef->enableMotor = FRONT_PRISM_JOINT_ENABLE_MOTOR;
frontPrismJointDef->lowerTranslation = FRONT_PRISM_JOINT_LOWERTRANSLATION;
frontPrismJointDef->upperTranslation = FRONT_PRISM_JOINT_UPPERTRANSLATION;
frontPrismJointDef->maxMotorForce = FRONT_PRISM_JOINT_MAXMOTORFORCE;
//b2Joint * joint = (b2Joint *)frontPrismJoint;
//frontPrismJointDef->
m_pFrontSpring = (b2PrismaticJoint *)m_pB2World->CreateJoint(frontPrismJointDef);
//m_pB2World->DestroyJoint(joint);
}
LHJoint * rearPrismJoint = rearDamper->jointWithUniqueName("RearDamperChasis");
type2 = rearPrismJoint->getType();
if(type2 == LH_PRISMATIC_JOINT)
{
//m_pRearPrismJoint = (b2PrismaticJoint *)rearPrismJoint;
rearPrismJointDef = new b2PrismaticJointDef();
rearPrismJointDef->Initialize(m_pChasis, m_pRearDamper, m_pRearDamper->GetWorldCenter(), b2Vec2(0, 1));
rearPrismJointDef->enableLimit = REAR_PRISM_JOINT_ENABLE_LIMIT;
rearPrismJointDef->enableMotor = REAR_PRISM_JOINT_ENABLE_MOTOR;
rearPrismJointDef->lowerTranslation = REAR_PRISM_JOINT_LOWERTRANSLATION;
rearPrismJointDef->upperTranslation = REAR_PRISM_JOINT_UPPERTRANSLATION;
rearPrismJointDef->maxMotorForce = REAR_PRISM_JOINT_MAXMOTORFORCE;
m_pRearSpring = (b2PrismaticJoint *)m_pB2World->CreateJoint(rearPrismJointDef);
}
LHJoint * frontRevoluteJoint = frontWheel->jointWithUniqueName("FrontDamperWheel");
//frontWheel->jo
LH_JOINT_TYPE type = frontRevoluteJoint->getType();
if(type == LH_REVOLUTE_JOINT)
{
m_pFrontMotor = (b2RevoluteJoint *)frontRevoluteJoint;
frontRevoluteJointDef = new b2RevoluteJointDef();
frontRevoluteJointDef->Initialize(m_pFrontDamper, m_pFrontWheel, m_pFrontWheel->GetWorldCenter());
frontRevoluteJointDef->motorSpeed = FRONT_REVOLUTE_JOINT_MOTORSPEED;
frontRevoluteJointDef->maxMotorTorque = FRONT_REVOLUTE_JOINT_MAXMOTORTORQUE;
frontRevoluteJointDef->enableMotor = FRONT_REVOLUTE_JOINT_ENABLE_MOTOR;
m_fFrontMotorSpeed = FRONT_REVOLUTE_JOINT_MOTORSPEED;
m_fFrontMaxMotorTorque = FRONT_REVOLUTE_JOINT_MAXMOTORTORQUE;
m_pFrontMotor = (b2RevoluteJoint *)m_pB2World->CreateJoint(frontRevoluteJointDef);
}
LHJoint * rearRevoluteJoint = rearWheel->jointWithUniqueName("RearDamperWheel");
type = rearRevoluteJoint->getType();
if(type == LH_REVOLUTE_JOINT)
{
//m_pRearRevoluteJoint = (b2RevoluteJoint *)rearRevoluteJoint;
rearRevoluteJointDef = new b2RevoluteJointDef();
rearRevoluteJointDef->Initialize(m_pRearDamper, m_pRearWheel, m_pRearWheel->GetWorldCenter());// - b2Vec2(0.1f,0.0f));
rearRevoluteJointDef->motorSpeed = REAR_REVOLUTE_JOINT_MOTORSPEED;
rearRevoluteJointDef->maxMotorTorque = REAR_REVOLUTE_JOINT_MAXMOTORTORQUE;
rearRevoluteJointDef->enableMotor = REAR_REVOLUTE_JOINT_ENABLE_MOTOR;
m_fRearMotorSpeed = REAR_REVOLUTE_JOINT_MOTORSPEED;
m_fRearMaxMotorTorque = REAR_REVOLUTE_JOINT_MAXMOTORTORQUE;
//revoluteJointDef.
m_pRearMotor = (b2RevoluteJoint *)m_pB2World->CreateJoint(rearRevoluteJointDef);
//m_fMotorSpeed = m_pRearMotor->GetMotorSpeed();
}
}
void GamePlayScene::ccTouchesBegan(cocos2d::CCSet *pTouches, CCEvent *pEvent)
{
CCTouch * touch = (CCTouch *)(pTouches->anyObject());
CCPoint location = touch->getLocationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
if(location.x > mSize.width/2)
{
bIsAcceleration = true;
bIsBrake = false;
m_pFrontMotor->EnableMotor(true);
m_pRearMotor->EnableMotor(true);
//m_pFrontWheel->SetLinearVelocity(b2Vec2(-20.0f, 0.0f));
direction = 1;
oppositeDirection = -1;
}
else
{
m_pFrontMotor->EnableMotor(true);
m_pRearMotor->EnableMotor(true);
bIsAcceleration = false;
bIsBrake = true;
direction = -1;
oppositeDirection = 1;
//m_pRearWheel->SetLinearVelocity(b2Vec2(25.0f, 0.0f));
}
}
void GamePlayScene::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent)
{
//bIsAcceleration=true;
}
void GamePlayScene::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
bIsAcceleration=false;
bIsBrake = false;
//direction *= -1;
//m_pFrontMotor->EnableMotor(false);
}
void GamePlayScene::clickOnBackwardButn(CCObject * pSender)
{
bIsAcceleration = false;
m_pFrontMotor->EnableMotor(false);
m_pRearMotor->EnableMotor(false);
//m_fMotorSpeed = 0.0;
m_pRearMotor->SetMotorSpeed(-50.0f);
m_pFrontMotor->SetMotorSpeed(-50.0f);
m_pRearMotor->SetMaxMotorTorque(50.0f);
m_pFrontMotor->SetMaxMotorTorque(50.0f);
//m_pRearWheel->SetLinearVelocity(b2Vec2(-(10.0f),0.0f));
}
void GamePlayScene::clickOnForwardButn(CCObject * pSender)
{
m_pFrontMotor->EnableMotor(true);
m_pRearMotor->EnableMotor(true);
bIsAcceleration = true;
//m_pFrontWheel->SetLinearVelocity(b2Vec2(15.0f + m_fVelocityAcceleration,0.0f));
}
void GamePlayScene::draw()
{
CCLayer::draw();
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
kmGLPushMatrix();
m_pB2World->DrawDebugData();
kmGLPopMatrix();
}
void GamePlayScene::update(float dt)
{
b2Vec2 position=m_pFrontWheel->GetPosition();
int x=position.x*32.0f;
int y=position.y*32.0f;
this->setPositionX(480.0f*90/100 + -x);
if(bIsAcceleration)
{
m_pFrontMotor->SetMotorSpeed(30 * M_PI * direction);
m_pFrontMotor->SetMaxMotorTorque(34);
m_pRearMotor->SetMotorSpeed(30 * M_PI * direction);
m_pRearMotor->SetMaxMotorTorque(24);
//m_pChasis->ApplyTorque(20 * direction);
}
else if(bIsBrake)
{
m_pFrontMotor->SetMotorSpeed(30 * M_PI * direction);
m_pFrontMotor->SetMaxMotorTorque(24);
m_pRearMotor->SetMotorSpeed(30 * M_PI * direction);
m_pRearMotor->SetMaxMotorTorque(34);
//m_pCarBody->ApplyTorque(30 * direction);
}
else
{
m_pFrontMotor->SetMotorSpeed(0.0f);
m_pFrontMotor->SetMaxMotorTorque(0.5f);
m_pRearMotor->SetMotorSpeed(0.0f);
m_pRearMotor->SetMaxMotorTorque(0.5f);
}
/*if(m_fMotorSpeed >= 50.0f)
{
m_fMotorSpeed = 50.0f;
}*/
m_pFrontSpring->SetMaxMotorForce(10 + abs(100 * pow(m_pFrontSpring->GetJointTranslation(), 2)));
m_pFrontSpring->SetMotorSpeed(-4*pow(m_pFrontSpring->GetJointTranslation(), 1));
m_pRearSpring->SetMaxMotorForce(30 + abs(100 * pow(m_pRearSpring->GetJointTranslation(), 2)));
m_pRearSpring->SetMotorSpeed((m_pRearSpring->GetMotorSpeed() - 10*m_pRearSpring->GetJointTranslation())*0.4);
int32 velocityIterations = 8;
int32 positionIterations = 6;
m_pB2World->Step(dt, velocityIterations, positionIterations);
}
void GamePlayScene::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}