DomainCollectionView not changing pages - silverlight-5.0

I'm trying to download lage amout of items from server and to avoid timeouts I'm using paging so what I tried to do is to load the first page and in my DomainCollectionView Loaded method call MoveToNextPage and so on untill all pages are loaded.
When I do that the DCV does not change from page, it remains on page 0, then I tried to refresh inside the PadeChanged event of the DCV but in there the PageIndex is -1 abd when I refresh the load operation is automatically cancelled.
this is my code:
private void OnLoadedPrintingModels(LoadOperation<AppointmentModel> op)
{
if (op.HasError)
{
MessageBox.Show(ApplicationStrings.PrintingConnectionError + Environment.NewLine + op.Error.Message);
op.MarkErrorAsHandled();
this.downloadDialog.Close();
this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
this.printingList.Clear();
this.printingDomainList.Source = null;
}
else if (!op.IsCanceled)
{
if (op.Entities.Any())
{
printingList.AddRange(op.Entities);
if (this.isStartingPrinting)
{
this.TotalPrintCount = op.TotalEntityCount;
this.TotalPrintCountD = (double)op.TotalEntityCount;
this.isStartingPrinting = false;
}
isDownloaded = true;
printingDomainList.Source = op.Entities;
printingDomainView.SetTotalItemCount(op.TotalEntityCount);
}
else
{
MessageBox.Show(ApplicationStrings.NoSearchResults);
isStartingPrinting = true;
this.downloadDialog.Close();
this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
this.printingList.Clear();
this.printingDomainList.Source = null;
DownloadedPrintingItems = 0.0;
}
}
else
{
MessageBox.Show(ApplicationStrings.PrintOperationCanceledByUser);
this.downloadPrintDataCanceled = false;
this.downloadDialog.Close();
this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
this.printingList.Clear();
this.printingDomainList.Source = null;
isStartingPrinting = true;
DownloadedPrintingItems = 0.0;
}
}
bool isDownloaded = false;
void printingDomainView_PageChanged(object sender, EventArgs e)
{
if (isDownloaded)
{
isDownloaded = false;
DownloadedPrintingItems = 100.0 * (double)printingList.Count / this.TotalPrintCountD;
if (printingList.Count < this.TotalPrintCount)
{
using (this.printingDomainView.DeferRefresh())
{
this.printingDomainView.PageSize = PrintingPageSize;
this.printingDomainView.MoveToNextPage();
}
}
else
{
isStartingPrinting = true;
this.downloadDialog.Close();
this.downloadDialog = null;
DownloadedPrintingItems = 0.0;
ConfirmPrintingResults();
}
}
}
I'm trying to do many things here but nothing seems to work. Any help on how to do this will be very appreciated.
Thank you very much in advance.

I finally solved the problem by waiting for DomainCollectionView.IsChangingPage inside a thread using async and await, the resultant code is this:
private **async** void OnLoadedPrintingModels(LoadOperation<AppointmentModel> op)
{
if (op.HasError)
{
MessageBox.Show(ApplicationStrings.PrintingConnectionError + Environment.NewLine + op.Error.Message);
op.MarkErrorAsHandled();
this.downloadDialog.Close();
this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
this.printingList.Clear();
this.printingDomainList.Source = null;
}
else if (!op.IsCanceled)
{
if (op.Entities.Any())
{
printingList.AddRange(op.Entities);
if (this.isStartingPrinting)
{
this.TotalPrintCount = op.TotalEntityCount;
this.TotalPrintCountD = (double)op.TotalEntityCount;
this.isStartingPrinting = false;
}
printingDomainList.Source = op.Entities;
printingDomainView.SetTotalItemCount(op.TotalEntityCount);
**await Task.Factory.StartNew(() =>
{
while (printingDomainView.IsPageChanging)
{
Thread.Sleep(1);
}
});**
DownloadedPrintingItems = 100.0 * (double)printingList.Count / this.TotalPrintCountD;
if (printingList.Count < this.TotalPrintCount)
{
using (this.printingDomainView.DeferRefresh())
{
this.printingDomainView.PageSize = PrintingPageSize;
this.printingDomainView.MoveToNextPage();
}
}
else
{
//this.IsBusy = false;
//this.WaitingMessage = ApplicationStrings.WaitLabel;
isStartingPrinting = true;
this.downloadDialog.Close();
//this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
DownloadedPrintingItems = 0.0;
//Thread.CurrentThread.Join(1);
ConfirmPrintingResults();
}
}
else
{
MessageBox.Show(ApplicationStrings.NoSearchResults);
isStartingPrinting = true;
this.downloadDialog.Close();
this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
this.printingList.Clear();
this.printingDomainList.Source = null;
DownloadedPrintingItems = 0.0;
}
}
else
{
MessageBox.Show(ApplicationStrings.PrintOperationCanceledByUser);
this.downloadPrintDataCanceled = false;
this.downloadDialog.Close();
this.TotalPrintCountD = 100.0;
this.downloadDialog = null;
this.printingList.Clear();
this.printingDomainList.Source = null;
isStartingPrinting = true;
DownloadedPrintingItems = 0.0;
}
}

Related

Make xpdf Pdf2Txt function as thread safe

I have tried to use xpdf source code into a MFC application to convert pdf to text. The code sample is taken from their site (or repository):
int Pdf2Txt(std::string PdfFile, std::string TxtFile) const
{
GString* ownerPW, *userPW;
UnicodeMap* uMap;
TextOutputDev* textOut;
TextOutputControl textOutControl;
GString* textFileName;
int exitCode;
char textEncName[128] = "";
char textEOL[16] = "";
GBool noPageBreaks = gFalse;
GBool quiet = gFalse;
char ownerPassword[33] = "\001";
char userPassword[33] = "\001";
int firstPage = 1;
int lastPage = 0;
GBool tableLayout = gFalse;
double fixedPitch = 0;
GBool physLayout = gFalse;
GBool simpleLayout = gFalse;
GBool simple2Layout = gFalse;
GBool linePrinter = gFalse;
GBool rawOrder = gFalse;
double fixedLineSpacing = 0;
double marginLeft = 0;
double marginRight = 0;
double marginTop = 0;
double marginBottom = 0;
GBool clipText = gFalse;
GBool discardDiag = gFalse;
GBool insertBOM = gFalse;
exitCode = 99;
// read config file
globalParams = new GlobalParams("");
if (textEncName[0])
{
globalParams->setTextEncoding(textEncName);
}
if (textEOL[0])
{
if (!globalParams->setTextEOL(textEOL))
{
fprintf(stderr, "Bad '-eol' value on command line\n");
}
}
if (noPageBreaks)
{
globalParams->setTextPageBreaks(gFalse);
}
if (quiet)
{
globalParams->setErrQuiet(quiet);
}
// Set UNICODE support
globalParams->setTextEncoding("UTF-8");
// get mapping to output encoding
if (!(uMap = globalParams->getTextEncoding()))
{
error(errConfig, -1, "Couldn't get text encoding");
goto err1;
}
// open PDF file
if (ownerPassword[0] != '\001')
{
ownerPW = new GString(ownerPassword);
}
else
{
ownerPW = NULL;
}
if (userPassword[0] != '\001')
{
userPW = new GString(userPassword);
}
else
{
userPW = NULL;
}
PDFDoc* doc = new PDFDoc((char*)PdfFile.c_str(), ownerPW, userPW);
if (userPW)
{
delete userPW;
}
if (ownerPW)
{
delete ownerPW;
}
if (! doc->isOk())
{
exitCode = 1;
goto err2;
}
// check for copy permission
if (! doc->okToCopy())
{
error(errNotAllowed, -1, "Copying of text from this document is not allowed.");
exitCode = 3;
goto err2;
}
// construct text file name
textFileName = new GString(TxtFile.c_str());
// get page range
if (firstPage < 1)
{
firstPage = 1;
}
if (lastPage < 1 || lastPage > doc->getNumPages())
{
lastPage = doc->getNumPages();
}
// write text file
if (tableLayout)
{
textOutControl.mode = textOutTableLayout;
textOutControl.fixedPitch = fixedPitch;
}
else if (physLayout)
{
textOutControl.mode = textOutPhysLayout;
textOutControl.fixedPitch = fixedPitch;
}
else if (simpleLayout)
{
textOutControl.mode = textOutSimpleLayout;
}
else if (simple2Layout)
{
textOutControl.mode = textOutSimple2Layout;
}
else if (linePrinter)
{
textOutControl.mode = textOutLinePrinter;
textOutControl.fixedPitch = fixedPitch;
textOutControl.fixedLineSpacing = fixedLineSpacing;
}
else if (rawOrder)
{
textOutControl.mode = textOutRawOrder;
}
else
{
textOutControl.mode = textOutReadingOrder;
}
textOutControl.clipText = clipText;
textOutControl.discardDiagonalText = discardDiag;
textOutControl.insertBOM = insertBOM;
textOutControl.marginLeft = marginLeft;
textOutControl.marginRight = marginRight;
textOutControl.marginTop = marginTop;
textOutControl.marginBottom = marginBottom;
textOut = new TextOutputDev(textFileName->getCString(), &textOutControl, gFalse, gTrue);
if (textOut->isOk())
{
doc->displayPages(textOut, firstPage, lastPage, 72, 72, 0, gFalse, gTrue, gFalse);
}
else
{
delete textOut;
exitCode = 2;
goto err3;
}
delete textOut;
exitCode = 0;
// clean up
err3:
delete textFileName;
err2:
delete doc;
// uMap->decRefCnt();
err1:
delete globalParams;
// check for memory leaks
Object::memCheck(stderr);
gMemReport(stderr);
return exitCode;
}
So far, so good. But this code isn't thread safe: if I am trying run this code inside a multi-threading code, it crashes:
// TextOutputDev.cc
if (uMap->isUnicode())
{
lreLen = uMap->mapUnicode(0x202a, lre, sizeof(lre)); // <-- crash
Why ? Because there is a variable, globalParams, which is deleted in the last lines of the function, and it's common for all threads:
delete globalParams;
And globalParams it's an extern global variable from GlobalParams.h (part of xpdf code):
// xpdf/GlobalParams.h
// The global parameters object.
extern GlobalParams *globalParams;
How can I do this function thread safe ? Because the "problem variable" it's inside xpdf source code, not in mine ...
P.S. To sum up things, globalParams it's declared in xpdf code, and it's cleaned in my (client) code.
The xpdf source code could be seen here:
https://github.com/jeroen/xpdf/blob/c2c946f517eb09cfd09d957e0f3b04d44bf6f827/src/poppler/GlobalParams.h
and
https://github.com/jeroen/xpdf/blob/c2c946f517eb09cfd09d957e0f3b04d44bf6f827/src/poppler/GlobalParams.cc
Try restructuring your code as shown below. I have moved the GlobalParams initialization code into a separate function. This function should be called (once) during initialization, or before starting the threads that call Pdf2Txt(). And of course the GlobalParams instance shouldn't be destroyed because it can be used by multiple threads. It won't hurt your app to keep it memory, it's one object anyway and not really large - well, it contains many int and bool member variables, but these do not take up much space, and quite a few string* variables (initially null or emtpy I guess), so it's just a few KB at most.
bool InitGlobalParams()
{
UnicodeMap* uMap;
char textEncName[128] = "";
char textEOL[16] = "";
GBool noPageBreaks = gFalse;
GBool quiet = gFalse;
// read config file
globalParams = new GlobalParams(""); // <-- Maybe add some checking code here?
if (textEncName[0])
{
globalParams->setTextEncoding(textEncName);
}
if (textEOL[0])
{
if (!globalParams->setTextEOL(textEOL))
{
fprintf(stderr, "Bad '-eol' value on command line\n");
}
}
if (noPageBreaks)
{
globalParams->setTextPageBreaks(gFalse);
}
if (quiet)
{
globalParams->setErrQuiet(quiet);
}
// Set UNICODE support
globalParams->setTextEncoding("UTF-8");
// get mapping to output encoding
if (!(uMap = globalParams->getTextEncoding()))
{
error(errConfig, -1, "Couldn't get text encoding");
return false;
}
return true;
}
int Pdf2Txt(std::string PdfFile, std::string TxtFile) const
{
GString* ownerPW, *userPW;
TextOutputDev* textOut;
TextOutputControl textOutControl;
GString* textFileName;
int exitCode;
char ownerPassword[33] = "\001";
char userPassword[33] = "\001";
int firstPage = 1;
int lastPage = 0;
GBool tableLayout = gFalse;
double fixedPitch = 0;
GBool physLayout = gFalse;
GBool simpleLayout = gFalse;
GBool simple2Layout = gFalse;
GBool linePrinter = gFalse;
GBool rawOrder = gFalse;
double fixedLineSpacing = 0;
double marginLeft = 0;
double marginRight = 0;
double marginTop = 0;
double marginBottom = 0;
GBool clipText = gFalse;
GBool discardDiag = gFalse;
GBool insertBOM = gFalse;
exitCode = 99;
// open PDF file
if (ownerPassword[0] != '\001')
{
ownerPW = new GString(ownerPassword);
}
else
{
ownerPW = NULL;
}
if (userPassword[0] != '\001')
{
userPW = new GString(userPassword);
}
else
{
userPW = NULL;
}
PDFDoc* doc = new PDFDoc((char*)PdfFile.c_str(), ownerPW, userPW);
if (userPW)
{
delete userPW;
}
if (ownerPW)
{
delete ownerPW;
}
if (! doc->isOk())
{
exitCode = 1;
goto err2;
}
// check for copy permission
if (! doc->okToCopy())
{
error(errNotAllowed, -1, "Copying of text from this document is not allowed.");
exitCode = 3;
goto err2;
}
// construct text file name
textFileName = new GString(TxtFile.c_str());
// get page range
if (firstPage < 1)
{
firstPage = 1;
}
if (lastPage < 1 || lastPage > doc->getNumPages())
{
lastPage = doc->getNumPages();
}
// write text file
if (tableLayout)
{
textOutControl.mode = textOutTableLayout;
textOutControl.fixedPitch = fixedPitch;
}
else if (physLayout)
{
textOutControl.mode = textOutPhysLayout;
textOutControl.fixedPitch = fixedPitch;
}
else if (simpleLayout)
{
textOutControl.mode = textOutSimpleLayout;
}
else if (simple2Layout)
{
textOutControl.mode = textOutSimple2Layout;
}
else if (linePrinter)
{
textOutControl.mode = textOutLinePrinter;
textOutControl.fixedPitch = fixedPitch;
textOutControl.fixedLineSpacing = fixedLineSpacing;
}
else if (rawOrder)
{
textOutControl.mode = textOutRawOrder;
}
else
{
textOutControl.mode = textOutReadingOrder;
}
textOutControl.clipText = clipText;
textOutControl.discardDiagonalText = discardDiag;
textOutControl.insertBOM = insertBOM;
textOutControl.marginLeft = marginLeft;
textOutControl.marginRight = marginRight;
textOutControl.marginTop = marginTop;
textOutControl.marginBottom = marginBottom;
textOut = new TextOutputDev(textFileName->getCString(), &textOutControl, gFalse, gTrue);
if (textOut->isOk())
{
doc->displayPages(textOut, firstPage, lastPage, 72, 72, 0, gFalse, gTrue, gFalse);
}
else
{
delete textOut;
exitCode = 2;
goto err3;
}
delete textOut;
exitCode = 0;
// clean up
err3:
delete textFileName;
err2:
delete doc;
// uMap->decRefCnt();
err1:
// Do NOT delete the one and only GlobalParams instance!!!
//delete globalParams;
// check for memory leaks
Object::memCheck(stderr);
gMemReport(stderr);
return exitCode;
}
The above code may not even compile (I modified it with a text editor, not really tested it) so please make any changes that may be required. It is quite expected that the xpdf functions do not modify the globalParams object (it's "read-only" for them) so this code has a good chance to work. Btw there is a #if MULTITHREADED directive in the GlobalParams class definition (GlobalParams.h) containing 3 mutex objects in its block. The implementation code (GlobalParams.cc) locks a mutex to access the GlobalParams members, so this may cause some threads to wait a little, although I can't tell how much (one would have to thoroughly examine the code, which is a small "project" in itself). You can try testing it.
Of course the concerns expressed by #KJ above still apply, running many such threads in parallel could overload the system (although i'm not sure if xpdf uses multiple threads to process a single PDF, could one help please, how is it configured?), esp if you are running this on a server do not allow too many concurrently-running conversions, it may cause other processes to slow down. It may also cause I/O bottleneck (disk and/or network), so experiment with few threads initially and check how it scales up.

Issues with AWS Lambda function, invoke error on cloudwatch

The Lambda Functions success VS. Errors
Hey Y'all I've scrubbed the internet to find the issues with my node.js function. The Cloudwatch error is the following. Any insight or suggestions would be massively helpful! The code runs but there are some issues. I do not know where the /var/runtime/CallbackContext.js code is which seems to be the source of the problem.
2019-12-11T16:34:24.328Z 0211ab2b-8fea-4391-9cc6-01f5c5244c63 ERROR Invoke Error
"errorType": "Error", " at _homogeneousError (/var/runtime/CallbackContext.js:13:12)",
" at postError (/var/runtime/CallbackContext.js:30:51)",
" at done (/var/runtime/CallbackContext.js:57:7)",
" at fail (/var/runtime/CallbackContext.js:69:7)",
" at Object.fail (/var/runtime/CallbackContext.js:105:16)",
" at /var/task/index.js:42:25",
" at IncomingMessage.<anonymous> (/var/task/index.js:444:13)",
" at IncomingMessage.emit (events.js:203:15)",
" at endReadableNT (_stream_readable.js:1143:12)",
" at process._tickCallback (internal/process/next_tick.js:63:19)"
]
Code:
Says the issues is line 42.25 which is the context.fail line.
if (error) {
logFailure(error, failedItems);
context.fail(JSON.stringify(error));
} else {
console.log('Success: ' + JSON.stringify(success));
context.succeed('Success');
}
// v1.1.2
var https = require('https');
var zlib = require('zlib');
var crypto = require('crypto');
var endpoint = 'vpc-esdxl-hx2nubxsqn3wh4hqwmywyy2g6y.us-east-1.es.amazonaws.com';
// Set this to true if you want to debug why data isn't making it to
// your Elasticsearch cluster. This will enable logging of failed items
// to CloudWatch Logs.
var logFailedResponses = false;
exports.handler = function(input, context) {
// decode input from base64
var zippedInput = Buffer.from(input.awslogs.data, 'base64');
// decompress the input
zlib.gunzip(zippedInput, function(error, buffer) {
if (error) { context.fail(error); return; }
// parse the input from JSON
var awslogsData = JSON.parse(buffer.toString('utf8'));
// transform the input to Elasticsearch documents
var elasticsearchBulkData = transform(awslogsData);
// skip control messages
if (!elasticsearchBulkData) {
console.log('Received a control message');
context.succeed('Control message handled successfully');
return;
}
// post documents to the Amazon Elasticsearch Service
post(elasticsearchBulkData, function(error, success, statusCode, failedItems) {
console.log('Response: ' + JSON.stringify({
"statusCode": statusCode
}));
if (error) {
logFailure(error, failedItems);
context.fail(JSON.stringify(error));
} else {
console.log('Success: ' + JSON.stringify(success));
context.succeed('Success');
}
});
});
};
function transform(payload) {
if (payload.messageType === 'CONTROL_MESSAGE') {
return null;
}
var bulkRequestBody = '';
payload.logEvents.forEach(function(logEvent) {
var timestamp = new Date(1 * logEvent.timestamp);
// index name format: atg-YYYY.MM.DD
var indexName = [
'atg-' + timestamp.getUTCFullYear(), // year
('0' + (timestamp.getUTCMonth() + 1)).slice(-2), // month
('0' + timestamp.getUTCDate()).slice(-2) // day
].join('.');
var source = buildSource(logEvent.message, logEvent.extractedFields);
var DXLRegex = /\#DXLORDER\#/;
// var LogDatetimeRegex = /(info|Error|Warning|debug)\t(Mon\s|Sun\s|Sat\s|Fri\s|Thu\s|Wed\s|Tue\s)(.*)\t([0-9])/;
var logtyperegex = /(info|Error|Warning|debug)/;
var WOrderRegex = /\|((W)[0-9][0-9][0-9][0-9][0-9][0-9][0-9])\|/;
var DXLOrderRegex = /(DXL([0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]))\|/;
var CustEMailRegex = /(DXL([0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]))\|\s*((.*)#(.*)(\.com|\.net|\.live|\.gov)\s*)\|/;
var EMailReferralRegex = /(#DXLORDER#)\|(SFMC),(\s*)(.*?)(\s*)\|(W[0-9]|\|[0-9])/;
var CouponRegex = /(DXL([0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])\|(((.*)#(.*(.com|.net|.live|)))\|)(.*)\|)/;
var atgpathregex = /(\/)(.*)(\t)/;
var carttotalregex = /(W[0-9][0-9][0-9][0-9][0-9][0-9][0-9]|null)\|(.*)\|([0-9]|[0-9][0-9]|[0-9][0-9][0-9])\.([0-9]|[0-9][0-9]|[0-9][0-9][0-9])\.([0-9]|[0-9][0-9]|[0-9][0-9][0-9])\.([0-9]|[0-9][0-9]|[0-9][0-9][0-9])\|(DXL)/;
var referralregex = /(#DXLORDER#)\s*\|\s*(.*)\s*,\s*(.*)\s*\|(W[0-9]|\|[0-9])/;
var ClientIPregex = /(([0-9][0-9]|[0-9][0-9][0-9]|[0-9])\.([0-9][0-9]|[0-9][0-9][0-9]|[0-9])\.([0-9][0-9]|[0-9][0-9][0-9]|[0-9])\.([0-9][0-9]|[0-9][0-9][0-9]|[0-9]))\|/;
var ATGIDRegex = /(20[0-9][0-9])(\t)(.*)(\t)(\/)/;
var EmailSegmentRegex = /([a-z]w)([0-9][0-9][0-9][0-9][0-9][0-9])_([0-9][0-9][0-9][0-9])_([A-Z]|[A-Z][A-Z])\|/;
var usernamesucregex = /(findUser: user )(.*)( found.)/;
var incorrectpassregex = /(Attempt to log into account )(.*)(with incorrect password)/;
var nonexistentregex = /(Attempt to log into nonexistent account )(.*)/;
var badcouponregex = /(noCouponFound: No coupon could be found for the claim code:)( )(.*)(.)/;
var ccauthamtregex = /(<R20_CC_AUTH_AMT>)(.*)(<\/R20_CC_AUTH_AMT>)/;
var couponremovedregex = /(in removeCoupon method : Coupon )(.*)( has been expired so removing couon from order )(.*)/;
var giftdollaramtregex = /(<GIFT_DOL>)( )(.*)(<\/GIFT_DOL.)/;
var giftredeemdollarregex = /(<GIFTCERT_REDEEM_DOL>)( )(.*)(<\/GIFTCERT_REDEEM_DOL>)/;
var itemnumregex = /(ITEM_NUM>)(([0-9][0-9][0-9][0-9][0-9] |[A-Z][0-9][0-9][0-9][0-9] )(.*)|HEM)((<\/[A-Z][0-9][0-9]_([0-9]|[0-9][0-9])_ITEM_NUM>))/;
var giftcardpinregex = /(<GIFT_CARD_PIN>)(.*)(<\/GIFT_CARD_PIN>)/;
var linkshareregex = /(#DXLORDER#)\s*\|\s*(linkshare)\s*,\s*(.*)\s*\|(W[0-9]|\|[0-9])/;
var giftcardnumregex = /<GIFT_CARD_NUM>(.*)<\/GIFT_CARD_NUM>/;
var giftcardprocesseddollarregex = /Payment Status in Payment Group,\sso using it.(.*):(.*)/;
var outofstockregex = /(We're sorry,\s*Item :\s*)(.*)\s([A-Z][0-9][0-9][0-9][0-9])(.*)/;
if(outofstockregex.exec(logEvent.message) != null){
var outofstockdesc = outofstockregex.exec(logEvent.message)[2];
var outofstockid = outofstockregex.exec(logEvent.message)[3];
} else{
outofstockdesc = "-";
outofstockid = "-";
}
if(giftcardprocesseddollarregex.exec(logEvent.message) != null){
var giftcardprocesseddollar = Number(giftcardprocesseddollarregex.exec(logEvent.message)[2]);
} else{
giftcardprocesseddollar = 0;
}
if(giftcardnumregex.exec(logEvent.message) != null){
var giftcardnum = giftcardnumregex.exec(logEvent.message)[1];
} else{
giftcardnum = "-";
}
// if(LogDatetimeRegex.exec(logEvent.message) != null){
// var datetimelog = Date(LogDatetimeRegex.exec(logEvent.message)[3]);
// } else {
// datetimelog = "-";
// }
if(DXLRegex.exec(logEvent.message) != null){
var DXLORDER = "DXLORDER";
} else {
DXLORDER = "False";
}
if(giftcardpinregex.exec(logEvent.message) != null){
var giftcardpin = giftcardpinregex.exec(logEvent.message)[2];
} else{
giftcardpin = "-";
}
if(itemnumregex.exec(logEvent.message) != null ){
var itemnum = itemnumregex.exec(logEvent.message)[3];
var itemdescr = itemnumregex.exec(logEvent.message)[4];
if(itemdescr == null && itemnumregex.exec(logEvent.message)[2] == "HEM"){
itemnum = "-";
itemdescr = "HEM";
}
} else {
itemnum = "-";
itemdescr ="-";
}
if(giftredeemdollarregex.exec(logEvent.message) != null){
var giftredeemdollaramt = giftredeemdollarregex.exec(logEvent.message)[3];
} else{
giftredeemdollaramt = "0";
}
if(giftdollaramtregex.exec(logEvent.message) != null){
var giftdollaramt = giftdollaramtregex.exec(logEvent.message)[3];
} else {
giftdollaramt = "0";
}
if(couponremovedregex.exec(logEvent.message) != null){
var removedcoupon = couponremovedregex.exec(logEvent.message)[2];
} else{
removedcoupon = "N/A";
}
if(couponremovedregex.exec(logEvent.message) != null){
var removedcouponorder = couponremovedregex.exec(logEvent.message)[4];
} else{
removedcouponorder = "N/A";
}
if(ccauthamtregex.exec(logEvent.message) != null){
var ccauthamt = ccauthamtregex.exec(logEvent.message)[2];
} else{
ccauthamt = "0";
}
if(badcouponregex.exec(logEvent.message) != null){
var badcoupon = badcouponregex.exec(logEvent.message)[3];
} else{
badcoupon = "-";
}
if(nonexistentregex.exec(logEvent.message) != null){
var nonexistent = nonexistentregex.exec(logEvent.message)[2];
} else{
nonexistent = "-";
}
if(incorrectpassregex.exec(logEvent.message) != null){
var incorrectpass = incorrectpassregex.exec(logEvent.message)[2];
} else{
incorrectpass = "-";
}
if(usernamesucregex.exec(logEvent.message) != null){
var username = usernamesucregex.exec(logEvent.message)[2];
} else{
username = "-";
}
if (EmailSegmentRegex.exec(logEvent.message)!=null){
var EmailMailing = EmailSegmentRegex.exec(logEvent.message)[1];
var EmailDate = EmailSegmentRegex.exec(logEvent.message)[2];
var EmailTime = EmailSegmentRegex.exec(logEvent.message)[3];
var EmailSegment = EmailSegmentRegex.exec(logEvent.message)[4];
} else{
EmailMailing = "-";
EmailDate = "-";
EmailTime = "-";
EmailSegment = "-";
}
if (ATGIDRegex.exec(logEvent.message)!=null && DXLRegex.exec(logEvent.message) != null){
var ATGID = ATGIDRegex.exec(logEvent.message)[3];
} else{
ATGID = "-";
}
if (ClientIPregex.exec(logEvent.message)!= null && DXLRegex.exec(logEvent.message) != null){
var ClientIP = ClientIPregex.exec(logEvent.message)[1];
} else{
ClientIP = "-";
}
if (referralregex.exec(logEvent.message) != null){
var referralsource = referralregex.exec(logEvent.message)[2];
var referral = referralregex.exec(logEvent.message)[3];
if (referralregex.exec(logEvent.message)[2].includes("linkshare") == true) {
referralsource = linkshareregex.exec(logEvent.message)[2];
referral = linkshareregex.exec(logEvent.message)[3];
}
} else{
referralsource = "-";
referral = "-";
}
if (carttotalregex.exec(logEvent.message) != null && DXLRegex.exec(logEvent.message) != null){
var carttotal = Number(carttotalregex.exec(logEvent.message)[2]);
} else {
carttotal = 0;
}
if (atgpathregex.exec(logEvent.message) != null && DXLRegex.exec(logEvent.message) != null){
var atgpath = atgpathregex.exec(logEvent.message)[0];
} else {
atgpath = "-";
}
if (CouponRegex.exec(logEvent.message) != null && DXLRegex.exec(logEvent.message) != null){
var Coupon = CouponRegex.exec(logEvent.message)[8];
var Coupon1 = Coupon.toUpperCase();
if(CouponRegex.exec(logEvent.message)[8] == "null"){
Coupon = "-";
}
} else {
Coupon = "-";
}
if (logtyperegex.exec(logEvent.message) != null){
var logtype = logtyperegex.exec(logEvent.message)[0];
} else{
logtype = "-";
}
if (EMailReferralRegex.exec(logEvent.message)!= null){
var EmailReferral = EMailReferralRegex.exec(logEvent.message)[4];
} else{
EmailReferral = "-";
}
if (CustEMailRegex.exec(logEvent.message)!= null && DXLRegex.exec(logEvent.message) != null){
var CustEMail = CustEMailRegex.exec(logEvent.message)[3];
} else{
CustEMail = "-";
}
if(DXLOrderRegex.exec(logEvent.message) != null && DXLRegex.exec(logEvent.message) != null){
var ATGOrderID = DXLOrderRegex.exec(logEvent.message)[1];
} else {
ATGOrderID = "-";
}
if(WOrderRegex.exec(logEvent.message)!= null && DXLRegex.exec(logEvent.message) != null){
var WOrder = WOrderRegex.exec(logEvent.message)[1];
} else{
WOrder = "-";
}
source['outofstockdesc'] = outofstockdesc;
source['outofstockid'] = outofstockid;
source['giftcardprocesseddollar'] = Number(1*giftcardprocesseddollar);
source['giftcardnum'] = giftcardnum;
source['DXLORDER'] = DXLORDER;
source['giftcardpin'] = giftcardpin;
source['itemnum'] = itemnum ;
source['itemdescr'] = itemdescr;
source['GiftcertRedeemDol'] = "$"+giftredeemdollaramt;
source['giftdollaramt']=giftdollaramt;
source['removedcoupon'] = removedcoupon;
source['removedcouponorder'] = removedcouponorder;
source['ccauthamt'] = ccauthamt;
source['badcoupon'] = badcoupon;
source['nonexistent'] = nonexistent;
source['incorrectpass'] = incorrectpass;
source['username'] = username;
source['EmailMailing'] = EmailMailing;
source['EmailDate']=EmailDate;
source['EmailTime'] = EmailTime;
source['EmailSegment'] = EmailSegment;
source['ATGID'] = ATGID;
source['ClientIP'] = ClientIP;
source['referral'] = referral;
source['referralsource'] = referralsource;
//source['carttotal'] = Number(1* carttotal);
source['carttotaldollar'] = Number(1* carttotal);
source['atgpath'] = atgpath;
source['Coupon'] = Coupon1;
source['logtype'] = logtype;
source['EMailReferral'] = EmailReferral;
source['CustomerEMail'] = CustEMail;
source['ATGOrderID'] = ATGOrderID;
source['WOrder'] = WOrder;
// source['datetimelog'] = new Date(datetimelog).toISOString();
source['#id'] = logEvent.id;
source['#timestamp'] = new Date(1 * logEvent.timestamp).toISOString();
source['#message'] = logEvent.message;
source['#owner'] = payload.owner;
source['#log_group'] = payload.logGroup;
source['#log_stream'] = payload.logStream;
var action = { "index": {} };
action.index._index = indexName;
action.index._type = payload.logGroup;
action.index._id = logEvent.id;
bulkRequestBody += [
JSON.stringify(action),
JSON.stringify(source),
].join('\n') + '\n';
});
return bulkRequestBody;
}
function buildSource(message, extractedFields) {
if (extractedFields) {
var source = {};
for (var key in extractedFields) {
if (extractedFields.hasOwnProperty(key) && extractedFields[key]) {
var value = extractedFields[key];
if (isNumeric(value)) {
source[key] = 1 * value;
continue;
}
jsonSubString = extractJson(value);
if (jsonSubString !== null) {
source['$' + key] = JSON.parse(jsonSubString);
}
source[key] = value;
}
}
return source;
}
jsonSubString = extractJson(message);
if (jsonSubString !== null) {
return JSON.parse(jsonSubString);
}
return {};
}
function extractJson(message) {
var jsonStart = message.indexOf('{');
if (jsonStart < 0) return null;
var jsonSubString = message.substring(jsonStart);
return isValidJson(jsonSubString) ? jsonSubString : null;
}
function isValidJson(message) {
try {
JSON.parse(message);
} catch (e) { return false; }
return true;
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function post(body, callback) {
var requestParams = buildRequest(endpoint, body);
var request = https.request(requestParams, function(response) {
var responseBody = '';
response.on('data', function(chunk) {
responseBody += chunk;
});
response.on('end', function() {
var info = JSON.parse(responseBody);
var failedItems;
var success;
if (response.statusCode >= 200 && response.statusCode < 299) {
failedItems = info.items.filter(function(x) {
return x.index.status >= 300;
});
success = {
"attemptedItems": info.items.length,
"successfulItems": info.items.length - failedItems.length,
"failedItems": failedItems.length
};
}
var error = response.statusCode !== 200 || info.errors === true ? {
"statusCode": response.statusCode,
"responseBody": responseBody
} : null;
callback(error, success, response.statusCode, failedItems);
});
}).on('error', function(e) {
callback(e);
});
request.end(requestParams.body);
}
function buildRequest(endpoint, body) {
var endpointParts = endpoint.match(/^([^\.]+)\.?([^\.]*)\.?([^\.]*)\.amazonaws\.com$/);
var region = endpointParts[2];
var service = endpointParts[3];
var datetime = (new Date()).toISOString().replace(/[:\-]|\.\d{3}/g, '');
var date = datetime.substr(0, 8);
var kDate = hmac('AWS4' + process.env.AWS_SECRET_ACCESS_KEY, date);
var kRegion = hmac(kDate, region);
var kService = hmac(kRegion, service);
var kSigning = hmac(kService, 'aws4_request');
var request = {
host: endpoint,
method: 'POST',
path: '/_bulk',
body: body,
headers: {
'Content-Type': 'application/json',
'Host': endpoint,
'Content-Length': Buffer.byteLength(body),
'X-Amz-Security-Token': process.env.AWS_SESSION_TOKEN,
'X-Amz-Date': datetime
}
};
var canonicalHeaders = Object.keys(request.headers)
.sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; })
.map(function(k) { return k.toLowerCase() + ':' + request.headers[k]; })
.join('\n');
var signedHeaders = Object.keys(request.headers)
.map(function(k) { return k.toLowerCase(); })
.sort()
.join(';');
var canonicalString = [
request.method,
request.path, '',
canonicalHeaders, '',
signedHeaders,
hash(request.body, 'hex'),
].join('\n');
var credentialString = [ date, region, service, 'aws4_request' ].join('/');
var stringToSign = [
'AWS4-HMAC-SHA256',
datetime,
credentialString,
hash(canonicalString, 'hex')
] .join('\n');
request.headers.Authorization = [
'AWS4-HMAC-SHA256 Credential=' + process.env.AWS_ACCESS_KEY_ID + '/' + credentialString,
'SignedHeaders=' + signedHeaders,
'Signature=' + hmac(kSigning, stringToSign, 'hex')
].join(', ');
return request;
}
function hmac(key, str, encoding) {
return crypto.createHmac('sha256', key).update(str, 'utf8').digest(encoding);
}
function hash(str, encoding) {
return crypto.createHash('sha256').update(str, 'utf8').digest(encoding);
}
function logFailure(error, failedItems) {
if (logFailedResponses) {
console.log('Error: ' + JSON.stringify(error, null, 2));
if (failedItems && failedItems.length > 0) {
console.log("Failed Items: " +
JSON.stringify(failedItems, null, 2));
}
}
}
I dont see a context.fail() function in the AWS docs
the callback() function takes two arguments: error, response.
Have you tried changing context to callback?:
if (error) {
logFailure(error, failedItems);
callback(error);
} else {
console.log('Success: ' + JSON.stringify(success));
callback(null, 'Success');
}
See Related

Cannot submit cmdbuffer using image ...

I'm trying to clear the the screen with a color, but I'm always getting an error
"Cannot submit cmd buffer using image (...) with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL.
And Actully i tried to modify some undefine values to depth_stenci_attachment optimal, but The only thing is I get is more of these errors. So is there a field,that is incorrectly filled, or I forget to fill?
So here is my full main.cpp Because I have no idea where the error could be.
#include<stdio.h>
#include<string.h>
#include<vector>
#define DEBUG
#ifdef _WIN32
#define VK_USE_PLATFORM_WIN32_KHR
#endif
#define KNOCH_JULIA 42
#include"window.h"
using namespace std;
#ifdef DEBUG
#include<iostream>
using namespace std;
VkDebugReportCallbackEXT report;
void init_debug(vulkan *vulk);
PFN_vkCreateDebugReportCallbackEXT fvkCreateDebugReportCallbackEXT = VK_NULL_HANDLE;
PFN_vkDestroyDebugReportCallbackEXT fvkDestroyDebugReportCallbackEXT = VK_NULL_HANDLE;
VKAPI_ATTR VkBool32 VKAPI_CALL callback(VkDebugReportFlagsEXT flag, VkDebugReportObjectTypeEXT obj_t, uint64_t src_obj, size_t loc, int32_t msg_code, const char* layer_pref, const char* msg, void* user_data) {
switch (flag) {
case VK_DEBUG_REPORT_ERROR_BIT_EXT:
cout<<"error!"<<" "<< flag<<" source:"<<src_obj<<"location: "<<loc<<": "<< msg<<endl;
break;
case VK_DEBUG_REPORT_WARNING_BIT_EXT:
cout << "warning!" << obj_t << ": " << msg << endl;
break;
}
return false;
}
void init_debug(vulkan *vulk) {
fvkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(vulk->inst, "vkCreateDebugReportCallbackEXT");
fvkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(vulk->inst, "vkDestroyDebugReportCallbackEXT");
if (nullptr == fvkCreateDebugReportCallbackEXT || nullptr == fvkDestroyDebugReportCallbackEXT) {
exit(-5);
}
VkDebugReportCallbackCreateInfoEXT info = {};
info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
info.pfnCallback = callback;
info.pNext = nullptr;
info.flags = VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_ERROR_BIT_EXT;
fvkCreateDebugReportCallbackEXT(vulk->inst, &info, nullptr, &report);
}
#endif
FILE *fileptr;
void initInstance(vulkan *vulk){
vector<char*> ext;
ext.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
ext.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.apiVersion = VK_MAKE_VERSION(1, 0, 39);
app_info.engineVersion = VK_MAKE_VERSION(0, 0, 1);
app_info.pApplicationName = "szar";
app_info.pEngineName = "yayitstarts";
app_info.pNext = nullptr;
VkInstanceCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
#ifdef DEBUG
vector<char*>layers;
layers.push_back("VK_LAYER_LUNARG_object_tracker");
layers.push_back("VK_LAYER_LUNARG_core_validation");
layers.push_back("VK_LAYER_LUNARG_parameter_validation");
//layers.push_back("VK_LAYER_LUNARG_vktrace");
layers.push_back("VK_LAYER_LUNARG_swapchain");
layers.push_back("VK_LAYER_LUNARG_image");
ext.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
#endif
#ifdef DEBUG
info.enabledLayerCount = layers.size();
info.ppEnabledLayerNames = layers.data();
#else
info.enabledLayerCount = 0;
info.ppEnabledLayerNames = nullptr;
#endif
info.pApplicationInfo = &app_info;
info.enabledExtensionCount = ext.size();
info.ppEnabledExtensionNames = ext.data();
info.flags = 0;
info.pNext = nullptr;
vkCreateInstance(&info, nullptr, &(vulk->inst));
}
void getGPU(vulkan *vulk) {
uint32_t dev_c=0;
vkEnumeratePhysicalDevices(vulk->inst,&dev_c,nullptr);
VkPhysicalDevice *gpus=(VkPhysicalDevice*)malloc(sizeof(VkPhysicalDevice)*dev_c);
vkEnumeratePhysicalDevices(vulk->inst, &dev_c, gpus);
vulk->gpu = gpus[0];
}
void createDevice(vulkan *vulk) {
VkPhysicalDeviceFeatures features;
vkGetPhysicalDeviceFeatures(vulk->gpu, &features);
float prior[] = { 1.0f };
uint32_t prop_c;
vkGetPhysicalDeviceQueueFamilyProperties(vulk->gpu, &prop_c, nullptr);
VkQueueFamilyProperties *props = (VkQueueFamilyProperties*)malloc(sizeof(VkQueueFamilyProperties)*prop_c);
vkGetPhysicalDeviceQueueFamilyProperties(vulk->gpu, &prop_c, props);
uint32_t index = -1;
for (int i = 0; i < prop_c; i++) {
VkBool32 supported;
vkGetPhysicalDeviceSurfaceSupportKHR(vulk->gpu, i, vulk->surface_struct.surface, &supported);
if (props[i].queueFlags&VK_QUEUE_GRAPHICS_BIT&&supported) {
index = i;
}
}
if (index == -1) {
printf("no graphic queue family found");
exit(-1);
}
#ifdef DEBUG
uint32_t count;
vkEnumerateInstanceLayerProperties(&count, nullptr);
vector<VkLayerProperties>layers_access(count);
vkEnumerateInstanceLayerProperties(&count, layers_access.data());
for (int i = 0; i < count; i++) {
printf("%s\n", layers_access[i].layerName);
}
uint32_t dev_count;
vkEnumerateDeviceLayerProperties(vulk->gpu, &dev_count, nullptr);
vector<VkLayerProperties>layers_access_dev(count);
vkEnumerateDeviceLayerProperties(vulk->gpu, &dev_count, layers_access.data());
for (int i = 0; i < dev_count; i++) {
printf("dev: %s\n", layers_access_dev[i].layerName);
}
#endif
vulk->queue_fam_ind = index;
int queue_count=1;
vector<char*> ext;
ext.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
#ifdef DEBUG
vector<char*> layers;
layers.push_back("VK_LAYER_LUNARG_object_tracker");
layers.push_back("VK_LAYER_LUNARG_core_validation");
#endif
VkDeviceQueueCreateInfo queue_info = {};
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pQueuePriorities = prior;
queue_info.queueCount = queue_count;
queue_info.queueFamilyIndex = index;
queue_info.flags = 0;
queue_info.pNext = nullptr;
VkDeviceCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
#ifdef DEBUG
info.enabledLayerCount = layers.size();
info.ppEnabledLayerNames = layers.data();
#else
info.enabledLayerCount = 0;
info.ppEnabledLayerNames = nullptr;
#endif
info.pEnabledFeatures = &features;
info.enabledExtensionCount = ext.size();
info.ppEnabledExtensionNames = ext.data();
info.pQueueCreateInfos = &queue_info;
info.queueCreateInfoCount = 1;
info.pNext = nullptr;
if (VK_SUCCESS != vkCreateDevice(vulk->gpu, &info, nullptr, &(vulk->device))) {
exit(-1);
}
vulk->queue = (VkQueue*)malloc(sizeof(VkQueue)*queue_count);
vkGetDeviceQueue(vulk->device, index, 0, &(vulk->queue[0]));
}
void createSwapchain(vulkan *vulk) {
VkSurfaceCapabilitiesKHR capabilities;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vulk->gpu, vulk->surface_struct.surface,&capabilities);
uint32_t format_c;
vkGetPhysicalDeviceSurfaceFormatsKHR(vulk->gpu, vulk->surface_struct.surface, &format_c, nullptr);
VkSurfaceFormatKHR *formats = (VkSurfaceFormatKHR*)malloc(sizeof(VkSurfaceFormatKHR)*format_c);
vkGetPhysicalDeviceSurfaceFormatsKHR(vulk->gpu, vulk->surface_struct.surface, &format_c, formats);
uint32_t pres_mode_c;
vkGetPhysicalDeviceSurfacePresentModesKHR(vulk->gpu, vulk->surface_struct.surface, &pres_mode_c, nullptr);
VkPresentModeKHR *pres_modes = (VkPresentModeKHR*)malloc(sizeof(VkPresentModeKHR)*pres_mode_c);
vkGetPhysicalDeviceSurfacePresentModesKHR(vulk->gpu, vulk->surface_struct.surface, &pres_mode_c, pres_modes);
int pres_mode_i = 0;
for (int i = 0; i < pres_mode_c; i++) {
if (pres_modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) {
pres_mode_i = i;
}
}
vulk->surface_struct.extent = capabilities.currentExtent;
vulk->image.color_format= formats[0].format;
VkSwapchainCreateInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
info.clipped = VK_TRUE;
info.compositeAlpha = (VkCompositeAlphaFlagBitsKHR)capabilities.supportedCompositeAlpha;
info.flags = 0;
info.imageArrayLayers=1;
info.imageColorSpace = formats[0].colorSpace;
info.imageExtent = capabilities.currentExtent;
info.imageFormat = formats[0].format;
info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
info.minImageCount = capabilities.minImageCount;
info.oldSwapchain =VK_NULL_HANDLE;
info.pNext = nullptr;
info.pQueueFamilyIndices =&(vulk->queue_fam_ind);
info.presentMode = pres_modes[pres_mode_i];
info.preTransform = capabilities.currentTransform;
info.queueFamilyIndexCount = 1;
info.surface = vulk->surface_struct.surface;
VkResult not_VK_SUCCESS = vkCreateSwapchainKHR(vulk->device, &info, nullptr, &(vulk->swapchain_struct.swapchain));
if (not_VK_SUCCESS != VK_SUCCESS) {
exit(-1);
}
vulk->swapchain_struct.format = formats[0].format;
}
void createImages(vulkan *vulk,Memory *depth_img_memory) {
uint32_t img_c;
vkGetSwapchainImagesKHR(vulk->device, vulk->swapchain_struct.swapchain, &img_c, nullptr);
vulk->image.color_images = (VkImage*)malloc(sizeof(VkImage)*img_c);
vkGetSwapchainImagesKHR(vulk->device, vulk->swapchain_struct.swapchain, &img_c, vulk->image.color_images);
vulk->image_c = img_c;
vulk->image.depth_images = (VkImage*)malloc(sizeof(VkImage));
vulk->image.color_image_views=(VkImageView*)malloc(sizeof(VkImageView)*img_c);
vulk->image.depth_image_views=(VkImageView*)malloc(sizeof(VkImageView));
VkComponentMapping mapping = {};
mapping.r = VK_COMPONENT_SWIZZLE_R;
mapping.g = VK_COMPONENT_SWIZZLE_G;
mapping.b = VK_COMPONENT_SWIZZLE_B;
mapping.a = VK_COMPONENT_SWIZZLE_A;
vulk->image.color_range = (VkImageSubresourceRange*)malloc(sizeof(VkImageSubresourceRange)*img_c);
VkImageSubresourceRange range = {};
range.aspectMask =VK_IMAGE_ASPECT_COLOR_BIT;
range.baseArrayLayer = 0;
range.baseMipLevel = 0;
range.layerCount = 1;
range.levelCount = 1;
for (int i = 0; i < img_c; i++) {
VkImageViewCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
info.components = mapping;
info.flags = 0;
info.format = vulk->swapchain_struct.format;
info.image = (vulk->image.color_images)[i];
info.pNext = nullptr;
info.subresourceRange = range;
info.viewType = VK_IMAGE_VIEW_TYPE_2D;
vulk->image.color_range[i] = range;
vkCreateImageView(vulk->device, &info, nullptr, &(vulk->image.color_image_views)[i]);
}
vulk->image.depth_range = (VkImageSubresourceRange*)malloc(sizeof(VkImageSubresourceRange));
vulk->image.depth_range[0] = range;
vector<VkFormat> depth_formats{
VK_FORMAT_D32_SFLOAT_S8_UINT,
VK_FORMAT_D32_SFLOAT,
VK_FORMAT_D24_UNORM_S8_UINT,
VK_FORMAT_D16_UNORM_S8_UINT,
VK_FORMAT_D16_UNORM
};
VkFormat depth_format;
for (int i = 0; i < depth_formats.size(); i++) {
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(vulk->gpu, depth_formats[i], &props);
if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
depth_format = depth_formats[i];
break;
}
}
vulk->image.depth_format = depth_format;
VkImageCreateInfo img_info = {};
img_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
img_info.arrayLayers = 1;
img_info.extent.width = vulk->surface_struct.extent.width;
img_info.extent.height = vulk->surface_struct.extent.height;
img_info.extent.depth = 1;
img_info.flags = 0;
img_info.format = depth_format;
img_info.imageType = VK_IMAGE_TYPE_2D;
img_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
img_info.mipLevels = 1;
img_info.pNext = nullptr;
img_info.pQueueFamilyIndices = &(vulk->queue_fam_ind);
img_info.queueFamilyIndexCount = 1;
img_info.samples = VK_SAMPLE_COUNT_1_BIT;
img_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
img_info.tiling = VK_IMAGE_TILING_OPTIMAL;
img_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
if (VK_SUCCESS!=vkCreateImage(vulk->device, &img_info, nullptr, &(vulk->image.depth_images)[0])) {
printf("It not works");
}
VkMemoryRequirements req;
vkGetImageMemoryRequirements(vulk->device, (vulk->image.depth_images)[0], &req);
vkGetPhysicalDeviceMemoryProperties(vulk->gpu, &(depth_img_memory->props));
uint32_t mem_index=-2;
for (int i = 0; i < depth_img_memory->props.memoryTypeCount; i++) {
if (req.memoryTypeBits & (1 << i)) {
if ((depth_img_memory->props.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
mem_index = i;
break;
}
}
}
if (mem_index == -2) {
printf("no supported memorytype");
exit(-2);
}
VkMemoryAllocateInfo mem_info = {};
mem_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mem_info.pNext = nullptr;
mem_info.allocationSize = req.size;
mem_info.memoryTypeIndex = mem_index;
vkAllocateMemory(vulk->device, &mem_info, nullptr, &(depth_img_memory->dev_mem));
vkBindImageMemory(vulk->device, (vulk->image.depth_images)[0], depth_img_memory->dev_mem, 0);
VkComponentMapping mapping_d = {
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
};
range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
VkImageViewCreateInfo img_view_info_d = {};
img_view_info_d.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
img_view_info_d.components = mapping_d;
img_view_info_d.flags = 0;
img_view_info_d.format = depth_format;
img_view_info_d.image = (vulk->image.depth_images)[0];
img_view_info_d.pNext = nullptr;
img_view_info_d.subresourceRange = range;
img_view_info_d.viewType = VK_IMAGE_VIEW_TYPE_2D;
if (VK_SUCCESS != vkCreateImageView(vulk->device, &img_view_info_d, nullptr, &(vulk->image.depth_image_views)[0])) {
printf("huge pile of shit!!!");
exit(-1);
}
}
void createCommandPool(vulkan vulk,cmd_pool *pool, uint32_t cmd_buff_c) {
VkCommandPoolCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT|VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
info.pNext = nullptr;
info.queueFamilyIndex = vulk.queue_fam_ind;
vkCreateCommandPool(vulk.device, &info, nullptr, &(pool->pool));
pool->cmd_buff_c = cmd_buff_c;
pool->cmd_buffs = (VkCommandBuffer*)malloc(sizeof(VkCommandBuffer) * cmd_buff_c);
VkCommandBufferAllocateInfo cmd_info = {};
cmd_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmd_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmd_info.commandPool = pool->pool;
cmd_info.commandBufferCount = cmd_buff_c ;
cmd_info.pNext = nullptr;
vkAllocateCommandBuffers(vulk.device, &cmd_info, pool->cmd_buffs);
}
VkClearValue *clear;
void createFramebuffer(vulkan *vulk,VkExtent2D extent) {
vulk->fbo = (VkFramebuffer*)malloc(sizeof(VkFramebuffer)*vulk->image_c);
for (int i = 0; i < vulk->image_c; i++) {
VkImageView *img_views = (VkImageView*)malloc(sizeof(VkImageView) * 2);
img_views[0] = vulk->image.color_image_views[i];
img_views[1] = vulk->image.depth_image_views[0];
VkFramebufferCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
info.attachmentCount = 2;
info.pAttachments = img_views;
info.width = extent.height;
info.height = extent.width;
info.layers = 1;
info.renderPass = vulk->render_pass;
info.flags = 0;
info.pNext = nullptr;
if (VK_SUCCESS != vkCreateFramebuffer(vulk->device, &info, nullptr, &(vulk->fbo[i]))) {
printf("could not create framebuffer");
}
}
}
VkSemaphore *semaphores;
void createSemaphore(vulkan *vulk ,VkSemaphore *semaphore) {
VkSemaphoreCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
info.pNext = nullptr;
info.flags = 0;
vkCreateSemaphore(vulk->device, &info, nullptr, semaphore);
}
void createRenderPass(vulkan *vulk) {
VkAttachmentDescription *descr = (VkAttachmentDescription*)malloc(sizeof(VkAttachmentDescription) * 2);
VkAttachmentDescription color_descr = {};
color_descr.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
color_descr.format = vulk->image.color_format;
color_descr.samples = VK_SAMPLE_COUNT_1_BIT;
color_descr.initialLayout= VK_IMAGE_LAYOUT_UNDEFINED;
color_descr.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_descr.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_descr.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_descr.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color_descr.flags = 0;
VkAttachmentDescription depth_descr = {};
depth_descr.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depth_descr.format = vulk->image.depth_format;
depth_descr.samples = VK_SAMPLE_COUNT_1_BIT;
depth_descr.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depth_descr.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depth_descr.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depth_descr.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depth_descr.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
depth_descr.flags = 0;
*descr = color_descr;
*(descr + 1) = depth_descr;
VkAttachmentReference color_ref = {};
color_ref.attachment = 0;
color_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_ref = {};
depth_ref.attachment = 1;
depth_ref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subp_descr = {};
subp_descr.colorAttachmentCount = 1;
subp_descr.pColorAttachments=&color_ref;
subp_descr.pDepthStencilAttachment = &depth_ref;
subp_descr.inputAttachmentCount = 0;
subp_descr.pInputAttachments = nullptr;
subp_descr.preserveAttachmentCount = 0;
subp_descr.pPreserveAttachments = nullptr;
subp_descr.pResolveAttachments = nullptr;
subp_descr.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subp_descr.flags = 0;
VkRenderPassCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
info.attachmentCount = 2;
info.pAttachments = descr;
info.dependencyCount = 0;
info.pDependencies = VK_NULL_HANDLE;
info.subpassCount = 1;
info.pSubpasses = &subp_descr;
info.flags = 0;
info.pNext = nullptr;
if (VK_SUCCESS != vkCreateRenderPass(vulk->device, &info, nullptr, &(vulk->render_pass))) {
printf("Could not create render pass.");
}
}
VkFence fence;
void createFences(vulkan *vulk) {
VkFenceCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
info.pNext = nullptr;
info.flags = 0;
vkCreateFence(vulk->device, &info, nullptr, &fence);
}
int main(int argc,char** argv) {
vulkan vulk;
Memory depth_memory;
cmd_pool pool;
initInstance(&vulk);
getGPU(&vulk);
Window window = Window();
window.open(&vulk);
createDevice(&vulk);
VkViewport viewport = {};
viewport.width = window.extent.width;
viewport.height = window.extent.height;
viewport.x = 0;
viewport.y = 0;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
init_debug(&vulk);
createSwapchain(&vulk);
createImages(&vulk, &depth_memory);
createRenderPass(&vulk);
createFramebuffer(&vulk,window.extent);
semaphores= (VkSemaphore*) malloc(sizeof(VkSemaphore)*2);
createSemaphore(&vulk, &semaphores[0]);
createSemaphore(&vulk, &semaphores[1]);
createFences(&vulk);
createCommandPool(vulk,&pool,2);
uint32_t img_pres;
VkResult result;
VkPresentInfoKHR info = {};
info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
info.pImageIndices = &img_pres;
info.pResults = &result;
info.swapchainCount = 1;
info.pSwapchains = &vulk.swapchain_struct.swapchain;
info.waitSemaphoreCount =0;
info.pWaitSemaphores = nullptr;
info.pNext = nullptr;
VkCommandBufferBeginInfo beg = {};
beg.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beg.pInheritanceInfo = nullptr;
beg.pNext = nullptr;
beg.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
VkClearValue val[2];
val[1] = { 0.0f,1.0f,1.0f,1.0f };
val[0] = { 0.0f,0 };
VkRenderPassBeginInfo render = {};
render.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render.clearValueCount = 2;
render.framebuffer = vulk.fbo[0];
render.pClearValues = val;
render.pNext = nullptr;
render.renderArea.offset = { 0,0 };
render.renderArea.extent = { window.extent.height, window.extent.width };
render.renderPass = vulk.render_pass;
vkBeginCommandBuffer(pool.cmd_buffs[0], &beg);
vkCmdBeginRenderPass(pool.cmd_buffs[0], &render, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(pool.cmd_buffs[0]);
vkEndCommandBuffer(pool.cmd_buffs[0]);
VkRenderPassBeginInfo render_2 = {};
render_2.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_2.clearValueCount = 2;
render_2.framebuffer = vulk.fbo[1];
render_2.pClearValues = val;
render_2.pNext = nullptr;
render_2.renderArea = { 0,0,window.extent.height,window.extent.width };
render_2.renderPass = vulk.render_pass;
vkBeginCommandBuffer(pool.cmd_buffs[1], &beg);
vkCmdBeginRenderPass(pool.cmd_buffs[1], &render_2, VK_SUBPASS_CONTENTS_INLINE);
vkCmdEndRenderPass(pool.cmd_buffs[1]);
vkEndCommandBuffer(pool.cmd_buffs[1]);
VkSubmitInfo sub = {};
sub.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
sub.commandBufferCount = 1;
sub.pNext = nullptr;
sub.pSignalSemaphores = nullptr;
sub.pWaitDstStageMask = nullptr;
sub.pWaitSemaphores = nullptr;
sub.signalSemaphoreCount = 0;
sub.waitSemaphoreCount = 0;
VkResult res=VK_ERROR_DEVICE_LOST;
sub.pCommandBuffers = &pool.cmd_buffs[0];
vkQueueSubmit(vulk.queue[0], 1, &sub, VK_NULL_HANDLE);
sub.pCommandBuffers = &pool.cmd_buffs[1];
vkQueueSubmit(vulk.queue[0], 1, &sub, VK_NULL_HANDLE);
while (window.running) {
if (VK_SUCCESS != vkAcquireNextImageKHR(vulk.device, vulk.swapchain_struct.swapchain, UINT64_MAX, VK_NULL_HANDLE, fence, &img_pres)) {
return -2;
}
vkWaitForFences(vulk.device, 1, &fence, VK_TRUE, UINT64_MAX);
vkResetFences(vulk.device, 1, &fence);vkQueueWaitIdle(vulk.queue[0]);
sub.pCommandBuffers = &pool.cmd_buffs[img_pres];
if (res == vkQueueSubmit(vulk.queue[0], 1, &sub, VK_NULL_HANDLE)) {
printf("img: %d\n",res);
}
cout << hex << vulk.image.depth_images[0] << endl;
vkQueuePresentKHR(vulk.queue[0], &info);
window.run();
}
return 0;
}
1) Update your SDK. There is even no VK_LAYER_LUNARG_image layer since 1.0.42.0. And you know, there was probably a bunchload of bugfixes.
2) You are enabling layers in wrong order. Use the VK_LAYER_LUNARG_standard_validation meta-layer instead of doing it manually (also avoids problem in 1 trying to use obsoleted layer).
3) I see many errors in your code. Layers do not necessarily have full coverage yet (and another uncought error may cause to show another error down the road that does not make sense without the context).
E.g. no synchronization (your semaphores are unused there), many memory leaks (due to C style programming), assuming there will be at least two swapchain images, not checking VkResults...
4) I cannot reproduce it with your code. Firstly I get a problem with having only one swapchain image and the code not expecting it (mentioned in 3). After fixing that I get error about vkAcquireNextImageKHR getting more images than allowed (driver layer bug if using VkPresentInfoKHR::pResults). Workarounding that I get no error messages.
I haven't checked your code exhaustively, but the renderpass says that both attachments are initially in UNDEFINED layout, transition to COLOR_ATTACHMENT_OPTIMAL/DEPTH_STENCIL_ATTACHMENT_OPTIMAL, and then finally to PRESENT_SRC/DEPTH_STENCIL_ATTACHMENT_OPTIMAL. That seems correct, and the validation layers appear to be ignoring the renderpass initialLayout settings. If you're seeing this on the most recent version of the SDK, please file a bug at https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers.

Arduino LCD game not displaying

I am getting crazy on my Snake LCD game.
I use an Arduino Mega and I'd like to use the LCD screen and the PmodKYPD for my Snake game. The problem is that it will not display anything, no matter which key I will press.
Here is my code:
#include <LiquidCrystal.h>
#include "Keypad.h"
byte mySnake[8][8] =
{
{ B00000,
B00000,
B00011,
B00110,
B01100,
B11000,
B00000,
},
{ B00000,
B11000,
B11110,
B00011,
B00001,
B00000,
B00000,
},
{ B00000,
B00000,
B00000,
B00000,
B00000,
B11111,
B01110,
},
{ B00000,
B00000,
B00011,
B01111,
B11000,
B00000,
B00000,
},
{ B00000,
B11100,
B11111,
B00001,
B00000,
B00000,
B00000,
},
{ B00000,
B00000,
B00000,
B11000,
B01101,
B00111,
B00000,
},
{ B00000,
B00000,
B01110,
B11011,
B11111,
B01110,
B00000,
},
{ B00000,
B00000,
B00000,
B01000,
B10000,
B01000,
B00000,
}
};
// keypad type definition
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] =
{{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'0','F','E','D'}};
byte rowPins[ROWS] = {
37, 36, 35, 34}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
33,32, 31, 30}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
boolean levelz[5][2][16] = {
{{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false},
{false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false}},
{{true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true},
{true,false,false,false,false,false,false,false,false,false,false,false,false,false,false,true}},
{{true,false,false,false,true,false,false,false,false,false,false,true,false,false,false,true},
{true,false,false,false,false,false,false,false,true,false,false,false,false,false,false,true}},
{{true,false,true,false,false,false,false,false,false,true,false,false,false,true,false,false},
{false,false,false,false,true,false,false,true,false,false,false,true,false,false,false,true}}
};
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
unsigned long time, timeNow;
int gameSpeed;
boolean skip, gameOver, gameStarted;
int olddir;
int selectedLevel,levels;
int NUM_KEYS = 5;
int adc_key_in;
int key=-1;
char key_read;
int oldkey=-1;
boolean x[16][80];
byte myChar[8];
byte nullChar[8] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0 };
boolean special;
struct partdef
{
int row,column,dir; //0 - up, 1 - down, 2 - right, 3 - left
struct partdef *next;
};
typedef partdef part;
part *head, *tail;
int i,j,collected;
long pc,pr;
void drawMatrix()
{
int cc=0;
if (!gameOver)
{
x[pr][pc] = true;
//for (i=0;i<8;i++) lcd.createChar(i, nullChar);
for(int r=0;r<2;r++)
{
for(int c=0;c<16;c++)
{
special = false;
for(int i=0;i<8;i++)
{
byte b=B00000;
if (x[r*8+i][c*5+0]) {b+=B10000; special = true;}
if (x[r*8+i][c*5+1]) {b+=B01000; special = true;}
if (x[r*8+i][c*5+2]) {b+=B00100; special = true;}
if (x[r*8+i][c*5+3]) {b+=B00010; special = true;}
if (x[r*8+i][c*5+4]) {b+=B00001; special = true;}
myChar[i] = b;
}
if (special)
{
lcd.createChar(cc, myChar);
lcd.setCursor(c,r);
lcd.write(byte(cc));
cc++;
}
else
{
lcd.setCursor(c,r);
if (levelz[selectedLevel][r][c]) lcd.write(255);
else lcd.write(254);
}
}
}
}
}
void freeList()
{
part *p,*q;
p = tail;
while (p!=NULL)
{
q = p;
p = p->next;
free(q);
}
head = tail = NULL;
}
void gameOverFunction()
{
delay(1000);
lcd.clear();
freeList();
lcd.setCursor(3,0);
lcd.print("Game Over!");
lcd.setCursor(4,1);
lcd.print("Score: ");
lcd.print(collected);
delay(1000);
}
void growSnake()
{
part *p;
p = (part*)malloc(sizeof(part));
p->row = tail->row;
p->column = tail->column;
p->dir = tail->dir;
p->next = tail;
tail = p;
}
void newPoint()
{
part *p;
p = tail;
boolean newp = true;
while (newp)
{
pr = random(16);
pc = random(80);
newp = false;
if (levelz[selectedLevel][pr / 8][pc / 5]) newp=true;
while (p->next != NULL && !newp)
{
if (p->row == pr && p->column == pc) newp = true;
p = p->next;
}
}
if (collected < 13 && gameStarted) growSnake();
}
void moveHead()
{
switch(head->dir) // 1 step in direction
{
case 0: head->row--; break;
case 1: head->row++; break;
case 2: head->column++; break;
case 3: head->column--; break;
default : break;
}
if (head->column >= 80) head->column = 0;
if (head->column < 0) head->column = 79;
if (head->row >= 16) head->row = 0;
if (head->row < 0) head->row = 15;
if (levelz[selectedLevel][head->row / 8][head->column / 5]) gameOver = true; // wall collision check
part *p;
p = tail;
while (p != head && !gameOver) // self collision
{
if (p->row == head->row && p->column == head->column) gameOver = true;
p = p->next;
}
if (gameOver)
gameOverFunction();
else
{
x[head->row][head->column] = true;
if (head->row == pr && head->column == pc) // point pickup check
{
collected++;
if (gameSpeed < 25) gameSpeed+=3;
newPoint();
}
}
}
void moveAll()
{
part *p;
p = tail;
x[p->row][p->column] = false;
while (p->next != NULL)
{
p->row = p->next->row;
p->column = p->next->column;
p->dir = p->next->dir;
p = p->next;
}
moveHead();
}
void createSnake(int n) // n = size of snake
{
for (i=0;i<16;i++)
for (j=0;j<80;j++)
x[i][j] = false;
part *p, *q;
tail = (part*)malloc(sizeof(part));
tail->row = 7;
tail->column = 39 + n/2;
tail->dir = 3;
q = tail;
x[tail->row][tail->column] = true;
for (i = 0; i < n-1; i++) // build snake from tail to head
{
p = (part*)malloc(sizeof(part));
p->row = q->row;
p->column = q->column - 1; //initial snake id placed horizoltally
x[p->row][p->column] = true;
p->dir = q->dir;
q->next = p;
q = p;
}
if (n>1)
{
p->next = NULL;
head = p;
}
else
{
tail->next = NULL;
head = tail;
}
}
void startF()
{
gameOver = false;
gameStarted = false;
selectedLevel = 1;
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Select level: 1");
for(i=0;i<8;i++)
{
lcd.createChar(i,mySnake[i]);
lcd.setCursor(i+4,1);
lcd.write(byte(i));
}
collected = 0;
gameSpeed = 8;
createSnake(3);
time = 0;
}
void setup()
{
levels = 5; //number of lvls
lcd.begin(16, 2);
startF();
}
void loop()
{
if (!gameOver && !gameStarted)
{
key_read = keypad.getKey(); // get key press
key = key_read - '0';
if (key != oldkey) // if keypress is detected
{
delay(50); // wait for debounce time
key_read = keypad.getKey(); // get key press
key = key_read - '0';
if (key != oldkey)
{
oldkey = key;
if (key >=0)
{
olddir = head->dir;
if (key==1 && selectedLevel<levels) selectedLevel++;
if (key==2 && selectedLevel>1) selectedLevel--;
if (key==4)
{
lcd.clear();
selectedLevel--;
newPoint();
gameStarted = true;
}
else
{
lcd.setCursor(14,0);
lcd.print(selectedLevel);
}
}
}
}
}
if (!gameOver && gameStarted)
{
skip = false; //skip the second moveAll() function call if the first was made
key_read = keypad.getKey(); // get key press
key = key_read - '0';
if (key != oldkey) // if keypress is detected
{
delay(50); // wait for debounce time
key_read = keypad.getKey(); // get key press
key = key_read - '0';
if (key != oldkey)
{
oldkey = key;
if (key >=0)
{
olddir = head->dir;
if (key==0 && head->dir!=3) head->dir = 2;
if (key==1 && head->dir!=1) head->dir = 0;
if (key==2 && head->dir!=0) head->dir = 1;
if (key==3 && head->dir!=2) head->dir = 3;
if (olddir != head->dir)
{
skip = true;
delay(1000/gameSpeed);
moveAll();
drawMatrix();
}
}
}
}
if (!skip)
{
timeNow = millis();
if (timeNow - time > 1000 / gameSpeed)
{
moveAll();
drawMatrix();
time = millis();
}
}
}
if(gameOver)
{
key_read = keypad.getKey(); // get key press
key = key_read - '0';
if (key != oldkey) // if keypress is detected
{
delay(50); // wait for debounce time
key_read = keypad.getKey(); // get key press
key = key_read - '0';
if (key != oldkey)
{
oldkey = key;
if (key >=0)
{
startF();
}
}
}
}
}
Does anyone know something about this issue?

Unhandled expcetion(Xutility) C++

I am using VS2012. I am writing a simple network game. Send/receve functions work fine. I don't understand why does program still throw the same exception at the same moment - when waitForOthers() function is completed. I toggled a lot of breakpoints and it looks like the program crashes after while loop is broken in this function BEFORE waitForOthersMove() in update fun.
Expcetion:
"First-chance exception at 0x64D1CCC8 (msvcp110d.dll) in StatkiKlient.exe: 0xC0000005: Access violation reading location 0x004B6CF4.
If there is a handler for this exception, the program may be safely continued."
xutility code which vs2012 points:
// MEMBER FUNCTIONS FOR _Container_base12
inline void _Container_base12::_Orphan_all()
{ // orphan all iterators
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy != 0)
{ // proxy allocated, drain it
_Lockit _Lock(_LOCK_DEBUG);
for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
HERE -> *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter) <- HERE
(*_Pnext)->_Myproxy = 0;
_Myproxy->_Myfirstiter = 0;
}
#endif /* _ITERATOR_DEBUG_LEVEL == 2 */
}
Here's the code:
"main.cpp":
#include "Client.h"
Client * client;
void clientLoop();
int main()
{
client = new Client();
clientLoop();
return 0;
}
void clientLoop()
{
while(true)
{
client->update();
}
}
"Client.cpp":
#include "Client.h"
Client::Client()
{
initialized = false;
me = new Gamer();
cnet = new ClientNetwork();
}
void Client::update()
{
if(!initialized)
waitForStart(); //here crashes
waitForOthersMove();
}
void Client::waitForOthersMove()
{
Packet packet;
char data[2000];
int iResult = 0;
std::cout<<"Oczekiwanie na przeciwnikow...\n\n";
while(true)
{
iResult = cnet->receveData(data, sizeof(Packet));
if(iResult < 0)
continue;
packet.deserialize(data);
if(packet.packet_type = YOUR_MOVE)
{
//action
break;
}
}
}
void Client::consoleInit() //only for tests
{
Gamer set_up;
Packet packet;
char data[2000];
set_up.nickname = "... " + me->id;
set_up.ships[0].dir = 2;
set_up.ships[0].size = 2;
set_up.ships[0].x = 0;
set_up.ships[0].y = 0;
set_up.ships[0].dir = 1;
set_up.ships[0].size = 2;
set_up.ships[0].x = 10;
set_up.ships[0].y = 15;
set_up.ships[0].dir = 2;
set_up.ships[0].size = 2;
set_up.ships[0].x = 0;
set_up.ships[0].y = 0;
set_up.ships[0].dir = 2;
set_up.ships[0].size = 2;
set_up.ships[0].x = 0;
set_up.ships[0].y = 0;
set_up.ships[0].dir = 2;
set_up.ships[0].size = 2;
set_up.ships[0].x = 0;
set_up.ships[0].y = 0;
set_up.ships[0].dir = 2;
set_up.ships[0].size = 2;
set_up.ships[0].x = 0;
set_up.ships[0].y = 0;
packet.player = set_up;
packet.serialize(data);
cnet->sendMessage(data, sizeof(Packet));
}
void Client::gameInit()
{
Packet packet;
char packet_data[2000];
initialized = true;
std::cout<<"My id: "<<me->id<<"\n";
packet.packet_type = GAME_INIT_R;
packet.serialize(packet_data);
cnet->sendMessage(packet_data, sizeof(Packet));
consoleInit();
std::cout<<"wyslano game_init_r\n";
}
void Client::waitForStart()
{
Packet packet;
int messageLength = 0;
printf("\nPołączono z serwerem. Oczekiwanie na pozostałych graczy...\n");
cnet->testConnection();
while(true)
{
messageLength = cnet->receveData(dataBuff, sizeof(Packet));
if(messageLength < 0)
continue;
packet.deserialize(dataBuff);
if(packet.packet_type = GAME_INIT)
{
me->id = packet.player.id;
gameInit();
printf("Initialized...");
break;
}
}
} - after this parenthesis exception is thorw(i toggled breakpoint here and after this in update function)