Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm getting a 'vector subscript out of range' error. I know this is caused by an indexing issue where the index is larger than the maximum size of the array/collection. However, I can't figure out why it's getting to that stage, as I am only ever incrementing the value by one, once in the entire project, and if it becomes larger than the size of the array, I reset it to 0. This is in regards to the frames of an animation in SDL. The index variable in question is m_currentFrame.
Here is the 'Process' method for the animated sprite, this is the only place in the entire project that calls 'm_currentFrame++', I did a ctrl+f search for it:
void
AnimatedSprite::Process(float deltaTime) {
// If not paused...
if (!m_paused){
// Count the time elapsed.
m_timeElapsed += deltaTime;
// If the time elapsed is greater than the frame speed.
if (m_timeElapsed > (float) m_frameSpeed){
// Move to the next frame.
m_currentFrame++;
// Reset the time elapsed counter.
m_timeElapsed = 0.0f;
// If the current frame is greater than the number
// of frame in this animation...
if (m_currentFrame > frameCoordinates.size()){
// Reset to the first frame.
m_currentFrame = 0;
// Stop the animation if it is not looping...
if (!m_loop) {
m_paused = true;
}
}
}
}
}
Here is the method (AnimatedSprite::Draw()), that is throwing the error:
void
AnimatedSprite::Draw(BackBuffer& backbuffer) {
// frame width
int frameWidth = m_frameWidth;
backbuffer.DrawAnimatedSprite(*this, frameCoordinates[m_currentFrame], m_frameWidth, m_frameHeight, this->GetTexture());
}
Here is a screenshot of the exact error:
error
if (m_currentFrame > frameCoordinates.size()){
// Reset to the first frame.
m_currentFrame = 0;
You already need to reset when m_currentFrame == frameCoordinates.size(), because the highest index of an array is its size minus one (counting begins at 0).
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points, return the minimum number of arrows that must be shot to burst all balloons
bool compare(vector<int> &a,vector<int> &b){
return a[1]<=b[1];
}
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
if(points.size()==1) return 1;
sort(points.begin(),points.end(),compare);
int arrows=1,end=points[0][1];
for(int i=1;i<points.size();i++){
if(points[i][0]>end){
arrows++;
end=points[i][1];
}
}
return arrows;
}
};
I am getting a runtime error:
Line 1034: Char 34: runtime error: applying non-zero offset 4 to null pointer (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
bool compare(vector<int> &a,vector<int> &b){
return a[1]<=b[1];
}
should be
bool compare(const vector<int> &a, const vector<int> &b){
return a[1]<b[1];
}
Comparators must define a strict weak ordering. One consequence of that is that they must return false for equal values, so <= is incorrect.
Looking at the error message however, I suspect that the immediate cause of your problems is that the vector points has size zero and so end=points[0][1] is an out of bounds vector access.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
When I am trying to access the bin values of a generated histogram of a greyscale image, I get this assertion failiure:
Error: Assertion failed (elemSize() == sizeof(_Tp)) in cv::Mat::at ... opencv2\core\mat.inl.hpp, line 943
This is the Code Fragment that throws the failiure:
for (int i = 0; i < 256; i++) {
hist.at<float>(i) = (hist.at<float>(i) / pixelAmount) * 255;
}
My main problem is that i dont really understand the problem associated with the assertion failiure
I looked up the OpenCV documentation for Histogram Calculation and they are accessing the histogram values the same way.
Thanks in advance for any advice
I'll assume that you got your hist Mat from another API call, so its type can't be affected at creation time.
The at<T>() method requires you to know the element type of the Mat (say, CV_8U), and to use that same type (uint8_t) in the access.
There are two ways to solve this situation:
get the scalar value (uint8_t), convert the scalar value so it suits your calculation, write back (uint8_t) a coerced value
convert the entire Mat to CV_32F, which is equivalent to float, and then do your operations
First option:
for (int i = 0; i < 256; i++) {
hist.at<uint8_t>(i) =
(static_cast<float>(hist.at<uint8_t>(i)) / pixelAmount) * 255;
}
Second option:
hist.convertTo(hist, CV_32F);
// now do your calculations with at<float>()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 10 months ago.
Improve this question
I have a simple 2D game of pool. You can give a ball some speed, and it'll move around and hit other balls. But I want a ball to stop eventually, so I added some acceleration, by running this code every frame:
balls[i].ax = -balls[i].vx * 0.1;
balls[i].ay = -balls[i].vy * 0.1;
...
if(hypot(balls[i].vx, balls[i].vy) < 0.2){
balls[i].vx = 0;
balls[i].vy = 0;
}
And it works... But I find it weird, not realistic. I have no physics knowledge, but I'm pretty sure friction should not depend on speed.
How can I improve physics of slowing down without too much complexity?
The rolling friction formula is this: F_k,r=μ_k,r_Fn. It only factors in the properties of the surface (μ_k) and the force on the ball (r_Fn). This should decelerate with a constant value, just adjust it until it looks roughly correct.
Example code:
x = 1 // mess around with this until it looks right
if (ball.xVelocity > x) { ball.xVelocity -= x } else { ball.xVelocity = 0 }
if (ball.yVelocity > x) { ball.yVelocity -= x } else { ball.yVelocity = 0 }
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am rendering different models. Big models (more than a thousand triangles) are rendered without issue, however small models(a single triangle, or 12 triangles) flicker.
The way I am currently rendering involves 2 passes, so I assume the flickering comes from an absence of proper barriers.
The execution goes:
start to render pass,
render to texture (image attachment of FB),
stop pass.
start pass,
render to main display
end pass.
There is only a single global graphics queue. Following the vulkan tutorial, I have a command buffer for every image in my swapchain, and I record commands to each buffer in that list, like so:
for(auto &cmd : cmd_buffers)
{
std::array<vk::ClearValue, 2> clears = {};
clears[0].color = vk::ClearColorValue(array<float, 4>({0,0,0,0}));
clears[1].depthStencil = vk::ClearDepthStencilValue(1.0f, 0.0f);
vk::RenderPassBeginInfo render_pass_info(
*render_pass, *(framebuffers[index]), {{0,0}, extent},
clears.size(), clears.data()
);
cmd.beginRenderPass(&render_pass_info, vk::SubpassContents::eInline);
index++;
}
/* submit more instructions to the command buffers later */
For the off screen target (FB) I only record a single command buffer.
I call my first render pass as described above, and then, immediately before calling the second render pass, I try waiting on an image barrier:
void RenderTarget::WaitForImage(VulkanImage* image)
{
vk::ImageMemoryBarrier barrier = {};
// TODO(undecided): maybe this isn't always true
barrier.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image->GetImage();
barrier.subresourceRange =
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1);
vk::CommandBuffer command_buffer = h_interface->BeginSingleTimeCommands();
command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllGraphics,
vk::PipelineStageFlagBits::eFragmentShader, {}, 0, nullptr, 0,
nullptr, 1, &barrier);
h_interface->EndSingleTimeCommands(command_buffer);
}
And then somewhere else in the code I call it:
display_target.WaitForImage(&image);
active_target_id = 0;
display_target.StartFrame();
render_presentation.AddDrawData(quad_buffer, {uniform_data},
{{&image, 1}});
display_target.EndFrame();
Based on the behaviour I have seen, I assume my issue is a synchronization problem, however, the image barrier code doesn't seem to solve the flickering.
Am I using the barrier wrong? Should I look into other possible sources of error (and if so, which)?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on a C++ program which should transfer a 2D image of a flame's intensity into a 3D model. The program is mainly working with multiple matrix-operations which I all realised using pointers (I know, I could use vectors though).
After the Input of the textfile, the mirroring and smoothing of the data values, there comes a correction calculation for each line of the image. At the beginning of the function for this calculation, the program stops on a random position but in the for-loop declaring the y_values-vector.
Here is the code-fragment:
void CorrectionCalculation(Matrix Matrix_To_Calculate, int n_values, int polynomial_degree, int n_rows)
{
for (int h = 0; h < n_rows; h++)
{
//Initialising and declaration of the y_values-vector, which is the copy of each matrix-line. This line is used for the correction-calculation.
double* y_values = new double(n_values);
for (int i = 0; i < n_values; i++)
{
y_values[i] = Matrix_To_Calculate[h][i];
}
//Initialisiing and declaration of the x-values (from 0 to Spiegelachse with stepwidth 1, because of the single Pixels)
double* x_values = new double(n_values);
for (int i = 0; i < n_values; i++)
{
x_values[i] = i;
}
When calculating a single line, the program worked fine. But when I added some code to calculate the whole image, the program stops.
You're not allocating an array of values, but a single element.
Instead of:
double* y_values = new double(n_values);
// ...
double* x_values = new double(n_values);
Change it to
double* y_values = new double[n_values];
//...
double* x_values = new double[n_values];
You should use a vector of doubles rather than array new. That way the memory will be automatically deleted when its no longer needed. E.g.:
#include <vector>
std::vector<double> y_values(y_values);
You're also hiding variables by using variable names the same as the parameters. This can lead to confusion and subtle bugs in code where you're not quite sure which variable is being changed.