bool RenderableWebEntityItem::buildWebSurface(EntityTreeRenderer* renderer) { if (_currentWebCount >= MAX_CONCURRENT_WEB_VIEWS) { qWarning() << "Too many concurrent web views to create new view"; return false; } qDebug() << "Building web surface"; ++_currentWebCount; // Save the original GL context, because creating a QML surface will create a new context QOpenGLContext * currentContext = QOpenGLContext::currentContext(); QSurface * currentSurface = currentContext->surface(); _webSurface = new OffscreenQmlSurface(); _webSurface->create(currentContext); _webSurface->setBaseUrl(QUrl::fromLocalFile(PathUtils::resourcesPath() + "/qml/")); _webSurface->load("WebEntity.qml"); _webSurface->resume(); _webSurface->getRootItem()->setProperty("url", _sourceUrl); _connection = QObject::connect(_webSurface, &OffscreenQmlSurface::textureUpdated, [&](GLuint textureId) { _texture = textureId; }); // Restore the original GL context currentContext->makeCurrent(currentSurface); auto forwardMouseEvent = [=](const RayToEntityIntersectionResult& intersection, const QMouseEvent* event) { // Ignore mouse interaction if we're locked if (this->getLocked()) { return; } if (event->button() == Qt::MouseButton::RightButton) { if (event->type() == QEvent::MouseButtonPress) { const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event); _lastPress = toGlm(mouseEvent->pos()); } } if (intersection.entityID == getID()) { if (event->button() == Qt::MouseButton::RightButton) { if (event->type() == QEvent::MouseButtonRelease) { const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event); ivec2 dist = glm::abs(toGlm(mouseEvent->pos()) - _lastPress); if (!glm::any(glm::greaterThan(dist, ivec2(1)))) { AbstractViewStateInterface::instance()->postLambdaEvent([this] { QMetaObject::invokeMethod(_webSurface->getRootItem(), "goBack"); }); } _lastPress = ivec2(INT_MIN); } return; } // FIXME doesn't work... double click events not received if (event->type() == QEvent::MouseButtonDblClick) { AbstractViewStateInterface::instance()->postLambdaEvent([this] { _webSurface->getRootItem()->setProperty("url", _sourceUrl); }); } if (event->button() == Qt::MouseButton::MiddleButton) { if (event->type() == QEvent::MouseButtonRelease) { AbstractViewStateInterface::instance()->postLambdaEvent([this] { _webSurface->getRootItem()->setProperty("url", _sourceUrl); }); } return; } // Map the intersection point to an actual offscreen pixel glm::vec3 point = intersection.intersection; glm::vec3 dimensions = getDimensions(); point -= getPosition(); point = glm::inverse(getRotation()) * point; point /= dimensions; point += 0.5f; point.y = 1.0f - point.y; point *= dimensions * (METERS_TO_INCHES * DPI); if (event->button() == Qt::MouseButton::LeftButton) { if (event->type() == QEvent::MouseButtonPress) { this->_pressed = true; this->_lastMove = ivec2((int)point.x, (int)point.y); } else if (event->type() == QEvent::MouseButtonRelease) { this->_pressed = false; } } if (event->type() == QEvent::MouseMove) { this->_lastMove = ivec2((int)point.x, (int)point.y); } // Forward the mouse event. QMouseEvent mappedEvent(event->type(), QPoint((int)point.x, (int)point.y), event->screenPos(), event->button(), event->buttons(), event->modifiers()); QCoreApplication::sendEvent(_webSurface->getWindow(), &mappedEvent); } }; _mousePressConnection = QObject::connect(renderer, &EntityTreeRenderer::mousePressOnEntity, forwardMouseEvent); _mouseReleaseConnection = QObject::connect(renderer, &EntityTreeRenderer::mouseReleaseOnEntity, forwardMouseEvent); _mouseMoveConnection = QObject::connect(renderer, &EntityTreeRenderer::mouseMoveOnEntity, forwardMouseEvent); _hoverLeaveConnection = QObject::connect(renderer, &EntityTreeRenderer::hoverLeaveEntity, [=](const EntityItemID& entityItemID, const MouseEvent& event) { if (this->_pressed && this->getID() == entityItemID) { // If the user mouses off the entity while the button is down, simulate a mouse release QMouseEvent mappedEvent(QEvent::MouseButtonRelease, QPoint(_lastMove.x, _lastMove.y), Qt::MouseButton::LeftButton, Qt::MouseButtons(), Qt::KeyboardModifiers()); QCoreApplication::sendEvent(_webSurface->getWindow(), &mappedEvent); } }); return true; }
void Recti::setBounds(int minX, int minY, int maxX, int maxY) { position = ivec2(minX, minY); size = ivec2(maxX - minX, maxY - minY); }
void main() { //Calculate the ray direction using viewport information vec3 rayDirection = frag_worldpos - RayOrigin; rayDirection = normalize(rayDirection); //Cube ray intersection test vec3 invR = 1.0 / rayDirection; vec3 tbot = invR * (volumeMin - RayOrigin); vec3 ttop = invR * (volumeMax - RayOrigin); //Now sort all elements of tbot and ttop to find the two min and max elements vec3 tmin = min(ttop, tbot); //Closest planes vec2 t = max(tmin.xx, tmin.yz); //Out of the closest planes, find the last to be entered (collision point) float tnear = max(t.x, t.y);//... //If the viewpoint is penetrating the volume, make sure to only cast the ray //from the eye position, not behind it tnear = max(0.0, tnear); //Now work out when the ray will leave the volume vec3 tmax = max(ttop, tbot); //Distant planes t = min(tmax.xx, tmax.yz);//Find the first plane to be exited float tfar = min(t.x, t.y);//... //Check what the screen depth is to make sure we don't sample the //volume past any standard GL objects float bufferDepth = texelFetch(DepthTexture, ivec2(gl_FragCoord.xy), 0).r; float depth = recalcZCoord(bufferDepth); tfar = min(depth, tfar); //We need to calculate the ray's starting position. We add a random //fraction of the stepsize to the original starting point to dither //the output float starting_offset = tnear; if (DitherRay != 0) starting_offset += StepSize * fract(sin(gl_FragCoord.x * 12.9898 + gl_FragCoord.y * 78.233) * 43758.5453); vec3 rayPos = RayOrigin + rayDirection * starting_offset; //The color accumulation variable vec4 color = vec4(0.0, 0.0, 0.0, 0.0); //Start the sampling by initialising the ray variables. We take the //first sample ready to integrate to the next sample vec4 first_sample = texture(DataTexture, (rayPos + 1.0) * 0.5); float lastsamplea = first_sample.a; vec4 lastTransfer = texture(IntTransferTexture, lastsamplea); vec3 lastnorm = first_sample.xyz * 2.0 - vec3(1.0); float lastnorm_length = length(lastnorm); lastnorm = (lastnorm_length == 0) ? -rayDirection : lastnorm / lastnorm_length; //Make this into the ray position step vector rayDirection *= StepSize; rayPos += rayDirection; for (float length = tfar - tnear; length > 0.0; length -= StepSize, rayPos += rayDirection) { //Grab the volume sample vec4 sample = texture(DataTexture, (rayPos - volumeMin) * invVolumeDimensions); float delta = sample.a - lastsamplea; vec4 transfer = texture(IntTransferTexture, sample.a); float deltaT = transfer.a - lastTransfer.a; vec3 deltaK = transfer.rgb - lastTransfer.rgb; vec4 src; if (delta == 0.0) { //Special case where the integration breaks down, just use the constant val. src = texture(TransferTexture, sample.a); src.a = (1.0 - exp( - StepSize * src.a)); } else { /*Pre-Integrated color calc*/ float opacity = 1.0 - exp( - deltaT * StepSize / delta); vec3 color = abs(deltaK) / (abs(deltaT) + 1.0e-10); src = vec4(color, opacity); } lastTransfer = transfer; lastsamplea = sample.a; ////////////Lighting calculations //We perform all the calculations in the eye space, The normal //from the previous step is used, as it is the normal in the //direction the ray entered the volume. vec3 norm = (ViewMatrix * vec4(lastnorm, 0.0)).xyz; src.rgb = calcLighting((ViewMatrix * vec4(rayPos,1.0)).xyz, norm, src.rgb); //Update the lastnormal with the new normal, if it is valid norm = sample.xyz * 2.0 - vec3(1.0); //Test if we've got a bad normal and need to reuse the old one float sqrnormlength = dot(norm,norm); norm /= sqrt(sqrnormlength); if (sqrnormlength >= 0.01) lastnorm = norm; ///////////Front to back blending src.rgb *= src.a; color = (1.0 - color.a) * src + color; //We only accumulate up to 0.95 alpha (the blending never //reaches 1). if (color.a >= 0.95) { //We have to renormalize the color by the alpha value (see //below) color.rgb /= color.a; //Set the alpha to one to make sure the pixel is not transparent color.a = 1.0; break; } } /*We must renormalize the color by the alpha value. For example, if our ray only hits just one white voxel with a alpha of 0.5, we will have src.rgb = vec4(1,1,1,0.5) src.rgb *= src.a; //which gives, src.rgb = 0.5 * src.rgb = vec4(0.5,0.5,0.5,0.5) color = (1.0 - color.a) * src + color; //which gives, color = (1.0 - 0) * vec4(0.5,0.5,0.5,0.5) + vec4(0,0,0,0) = vec4(0.5,0.5,0.5,0.5) So the final color of the ray is half way between white and black, but the voxel it hit was white! The solution is to divide by the alpha, as this is the "amount of color" added to color. */ color.rgb /= float(color.a == 0.0) + color.a; color_out = color; });
Sphere(float radius) : m_radius(radius) { ParametricInterval interval = { ivec2(20, 20), vec2(Pi, TwoPi), vec2(40, 70) }; SetInterval(interval); }
MobiusStrip(float scale) : m_scale(scale) { ParametricInterval interval = { ivec2(40, 20), vec2(TwoPi, TwoPi), vec2(40, 15) }; SetInterval(interval); }
void QtCanvas::resizeGL(int w, int h) { sizeChanged(ivec2(w, h)); }
void TransferFunctionPropertyDialog::resizeEvent(QResizeEvent* event) { setEditorDimensions(ivec2(event->size().width(), event->size().height())); QWidget::resizeEvent(event); updateTFPreview(); }
void Camera::setViewport(int width, int height) { return setViewport(ivec2(width, height)); }
void RenderableWebEntityItem::render(RenderArgs* args) { QOpenGLContext * currentContext = QOpenGLContext::currentContext(); QSurface * currentSurface = currentContext->surface(); if (!_webSurface) { _webSurface = new OffscreenQmlSurface(); _webSurface->create(currentContext); _webSurface->setBaseUrl(QUrl::fromLocalFile(PathUtils::resourcesPath() + "/qml/")); _webSurface->load("WebEntity.qml"); _webSurface->resume(); _webSurface->getRootItem()->setProperty("url", _sourceUrl); _connection = QObject::connect(_webSurface, &OffscreenQmlSurface::textureUpdated, [&](GLuint textureId) { _webSurface->lockTexture(textureId); assert(!glGetError()); // TODO change to atomic<GLuint>? withLock(_textureLock, [&] { std::swap(_texture, textureId); }); if (textureId) { _webSurface->releaseTexture(textureId); } if (_texture) { _webSurface->makeCurrent(); glBindTexture(GL_TEXTURE_2D, _texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); _webSurface->doneCurrent(); } }); auto forwardMouseEvent = [=](const RayToEntityIntersectionResult& intersection, const QMouseEvent* event, unsigned int deviceId) { // Ignore mouse interaction if we're locked if (this->getLocked()) { return; } if (event->button() == Qt::MouseButton::RightButton) { if (event->type() == QEvent::MouseButtonPress) { const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event); _lastPress = toGlm(mouseEvent->pos()); } } if (intersection.entityID == getID()) { if (event->button() == Qt::MouseButton::RightButton) { if (event->type() == QEvent::MouseButtonRelease) { const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event); ivec2 dist = glm::abs(toGlm(mouseEvent->pos()) - _lastPress); if (!glm::any(glm::greaterThan(dist, ivec2(1)))) { AbstractViewStateInterface::instance()->postLambdaEvent([this] { QMetaObject::invokeMethod(_webSurface->getRootItem(), "goBack"); }); } _lastPress = ivec2(INT_MIN); } return; } // FIXME doesn't work... double click events not received if (event->type() == QEvent::MouseButtonDblClick) { AbstractViewStateInterface::instance()->postLambdaEvent([this] { _webSurface->getRootItem()->setProperty("url", _sourceUrl); }); } if (event->button() == Qt::MouseButton::MiddleButton) { if (event->type() == QEvent::MouseButtonRelease) { AbstractViewStateInterface::instance()->postLambdaEvent([this] { _webSurface->getRootItem()->setProperty("url", _sourceUrl); }); } return; } // Map the intersection point to an actual offscreen pixel glm::vec3 point = intersection.intersection; point -= getPosition(); point = glm::inverse(getRotation()) * point; point /= getDimensions(); point += 0.5f; point.y = 1.0f - point.y; point *= getDimensions() * METERS_TO_INCHES * DPI; // Forward the mouse event. QMouseEvent mappedEvent(event->type(), QPoint((int)point.x, (int)point.y), event->screenPos(), event->button(), event->buttons(), event->modifiers()); QCoreApplication::sendEvent(_webSurface->getWindow(), &mappedEvent); } }; EntityTreeRenderer* renderer = static_cast<EntityTreeRenderer*>(args->_renderer); QObject::connect(renderer, &EntityTreeRenderer::mousePressOnEntity, forwardMouseEvent); QObject::connect(renderer, &EntityTreeRenderer::mouseReleaseOnEntity, forwardMouseEvent); QObject::connect(renderer, &EntityTreeRenderer::mouseMoveOnEntity, forwardMouseEvent); } glm::vec2 dims = glm::vec2(getDimensions()); dims *= METERS_TO_INCHES * DPI; // The offscreen surface is idempotent for resizes (bails early // if it's a no-op), so it's safe to just call resize every frame // without worrying about excessive overhead. _webSurface->resize(QSize(dims.x, dims.y)); currentContext->makeCurrent(currentSurface); PerformanceTimer perfTimer("RenderableWebEntityItem::render"); Q_ASSERT(getType() == EntityTypes::Web); static const glm::vec2 texMin(0.0f), texMax(1.0f), topLeft(-0.5f), bottomRight(0.5f); Q_ASSERT(args->_batch); gpu::Batch& batch = *args->_batch; batch.setModelTransform(getTransformToCenter()); bool textured = false, culled = false, emissive = false; if (_texture) { batch._glActiveBindTexture(GL_TEXTURE0, GL_TEXTURE_2D, _texture); textured = emissive = true; } DependencyManager::get<DeferredLightingEffect>()->bindSimpleProgram(batch, textured, culled, emissive); DependencyManager::get<GeometryCache>()->renderQuad(batch, topLeft, bottomRight, texMin, texMax, glm::vec4(1.0f)); }
void Histogram2D::Build(VData&data,VData&data2) { hist_size = ivec2(1024,256); chunk_size.y = wxGetNumberFromUser( "Enter chunk size for the second field", _T("Enter a number(>=0, 0 to automatic maximum detection):"), _T("Numeric input"), chunk_size.y, 0, 2024, 0 ); ivec3 data_size = data.GetSize(); ivec3 data_size2 = data2.GetSize(); if(!chunk_size.y) { unsigned int max2=0; for(int i=0;i<data_size2.x;i++) for(int j=0;j<data_size2.y;j++) for(int k=0;k<data_size2.z;k++) { unsigned int val = data2.GetValue(i,j,k); if(max2<val)max2=val; } chunk_size.y = max(1,max2/hist_size.y); } mag_scale = (float)(hist_size.y*chunk_size.y)/(float)(256*256); if(hist)delete[]hist; hist = new unsigned int[hist_size.x*hist_size.y]; memset(hist,0,hist_size.x*hist_size.y*sizeof(int)); int max_h = data_size.x*data_size.y*data_size.z/(hist_size.y*hist_size.x); if(!max_h)max_h=1; for(int i=0;i<data_size.x;i+=2) for(int j=0;j<data_size.y;j+=2) for(int k=0;k<data_size.z;k+=2) { unsigned int val = data.GetValue(i,j,k); int i1 = (i*data_size2.x)/data_size.x; int j1 = (j*data_size2.y)/data_size.y; int k1 = (k*data_size2.z)/data_size.z; if(i1>=data_size2.x)i1=data_size2.x-1; if(j1>=data_size2.y)j1=data_size2.y-1; if(k1>=data_size2.z)k1=data_size2.z-1; unsigned int tmpv = val/chunk_size.x; unsigned int grad_mag = data2.GetValue(i1,j1,k1)/chunk_size.y; // tmpv=rand()%hist_size.x; // grad_mag=rand()%hist_size.y; if(tmpv>=0 && tmpv<hist_size.x && grad_mag<hist_size.y) { int id = tmpv+grad_mag*hist_size.x; if(rand()%max_h > hist[id]) hist[id]++; } } max_chunk = 0; unsigned int *hh = hist; for(int i=0;i<hist_size.x*hist_size.y;i++,hh++) { if(max_chunk<*hh)max_chunk=*hh; } //UpdateTexture(); need_reload_txt=1; }
void gamma_correct(palette *&pal, int force_menu) { long dg=0,old_dg=0; int abort=0; // see if user has already done this routine LSymbol *gs = LSymbol::Find("darkest_gray"); if(old_pal) { delete pal; pal = old_pal; old_pal = NULL; } if(gs && DEFINEDP(gs->GetValue()) && !force_menu) { dg = lnumber_value(gs->GetValue()); } #ifdef __QNXNTO__ else if (!force_menu) { dg = 36; } #endif // __QNXNTO__ else { if(gs && DEFINEDP(gs->GetValue())) { dg = old_dg = lnumber_value(gs->GetValue()); } // load in a fine gray palette they can chose from palette *gray_pal = pal->copy(); int i = 0; int tc = 32; for(; i < tc; i++) { gray_pal->set(i, i * 4, i * 4, i * 4); } gray_pal->load(); int wm_bc = wm->bright_color(), wm_mc = wm->medium_color(), wm_dc = wm->dark_color(); int br_r = pal->red(wm_bc) + 20; if(br_r > 255) br_r = 255; int br_g = pal->green(wm_bc) + 20; if(br_g > 255) br_g = 255; int br_b = pal->blue(wm_bc) + 20; if(br_b > 255) br_b = 255; int md_r = pal->red(wm_mc) - 20; if(md_r < 0) md_r = 0; int md_g = pal->green(wm_mc) - 20; if(md_g < 0) md_g = 0; int md_b = pal->blue(wm_mc) - 20; if(md_b < 0) md_b = 0; int dr_r = pal->red(wm_dc) - 40; if(dr_r < 0) dr_r = 0; int dr_g = pal->green(wm_dc) - 40; if(dr_g < 0) dr_g = 0; int dr_b = pal->blue(wm_dc) - 40; if(dr_b < 0) dr_b = 0; wm->set_colors(gray_pal->find_closest(br_r, br_g, br_b), gray_pal->find_closest(md_r, md_g, md_b), gray_pal->find_closest(dr_r, dr_g, dr_b)); int sh = wm->font()->Size().y + 35; button *but = new button(5, 5 + sh * 3, ID_GAMMA_OK, cache.img(ok_button), new info_field(35, 10 + sh * 3, ID_NULL, lang_string("gamma_msg"), 0)); gray_picker *gp = new gray_picker(2, 5 + sh, ID_GREEN_PICKER, 0, dg / 4, but); gp->set_pos(dg / 4); Jwindow *gw = wm->CreateWindow(ivec2(xres / 2 - 190, yres / 2 - 90), ivec2(-1), gp); Event ev; wm->flush_screen(); do { do { wm->get_event(ev); } while(ev.type == EV_MOUSE_MOVE && wm->IsPending()); wm->flush_screen(); if(ev.type == EV_CLOSE_WINDOW) abort = 1; if(ev.type == EV_KEY && ev.key == JK_ESC) abort = 1; } while(!abort && (ev.type != EV_MESSAGE || ev.message.id != ID_GAMMA_OK)); dg = ((spicker *)gw->inm->get(ID_GREEN_PICKER))->first_selected() * 4; wm->close_window(gw); wm->flush_screen(); wm->set_colors(wm_bc, wm_mc, wm_dc); delete gray_pal; if(!abort) { char *gammapath; FILE *fp; gammapath = (char *)malloc(strlen(get_save_filename_prefix()) + 10); sprintf(gammapath, "%sgamma.lsp", get_save_filename_prefix()); fp = open_FILE(gammapath, "wb"); if(fp) { fprintf(fp, "(setq darkest_gray %ld)\n", dg); fclose(fp); LSpace *sp = LSpace::Current; LSpace::Current = &LSpace::Perm; LSymbol::FindOrCreate("darkest_gray")->SetNumber(dg); LSpace::Current = sp; } else { dprintf("Unable to write to file gamma.lsp\n"); } free(gammapath); } } if(abort) dg = old_dg; if(dg < 1) dg = 1; else if(dg > 128) dg = 128; double gamma = log(dg / 255.0) / log(16.0 / 255.0); old_pal = pal; pal = new palette; for(int i = 0; i < 256; i++) { uint8_t oldr, oldg, oldb; old_pal->get(i, oldr, oldg, oldb); pal->set(i, (int)(pow(oldr / 255.0, gamma) * 255), (int)(pow(oldg / 255.0, gamma) * 255), (int)(pow(oldb / 255.0, gamma) * 255)); } pal->load(); }
void RenderGame() { if (void* data = gpu::Map(gRectVb)) { memcpy(data, gRectVerts, gRectVertCount * sizeof(Vertex)); gpu::Unmap(gRectVb); } if (void* data = gpu::Map(gFontVb)) { memcpy(data, gFontVerts, gFontVertCount * sizeof(Vertex)); gpu::Unmap(gFontVb); } if (void* data = gpu::Map(gTriVb)) { memcpy(data, gTriVerts, gTriVertCount * sizeof(Vertex)); gpu::Unmap(gTriVb); } // draw gpu::SetRenderTarget(g_draw_target); gpu::SetDepthTarget(g_depth_target); gpu::SetViewport(ivec2(0, 0), g_WinSize, vec2(0.0f, 1.0f)); gpu::Clear(0x00000000); gpu::SetDepthMode(true); gpu::SetVsConst(0, gProj * gCam3d); gpu::Draw(gSolidDecl, gTriVb, gTriVertCount, true, false); gpu::SetDepthMode(false); gpu::SetVsConst(0, gCam); gpu::SetTexture(0, g_sheet); gpu::SetSampler(0, true, false); gpu::Draw(gTexDecl, gRectVb, gRectVertCount, true, false); gpu::SetTexture(0, g_font); gpu::SetSampler(0, true, false); gpu::Draw(gTexDecl, gFontVb, gFontVertCount, true, false); gpu::SetDepthTarget(0); for(int i = 0; i < MAX_BLOOM_LEVELS; i++) { bloom_level* bl = g_bloom_levels + i; // reduce gpu::SetRenderTarget(bl->reduce); gpu::SetViewport(ivec2(), bl->size, vec2(0.0f, 1.0f)); gpu::SetTexture(0, (i == 0) ? g_draw_target : g_bloom_levels[i - 1].blur_y); gpu::SetSampler(0, true, true); gpu::SetPsConst(0, vec4(1.0f / to_vec2(bl->size), 0.0f, 0.0f)); do_fullscreen_quad(gReduceDecl, to_vec2(bl->size)); // blur x gpu::SetRenderTarget(bl->blur_x); gpu::SetViewport(ivec2(), bl->size, vec2(0.0f, 1.0f)); gpu::SetTexture(0, bl->reduce); gpu::SetSampler(0, true, true); gpu::SetPsConst(0, vec4(1.0f / to_vec2(bl->size), 0.0f, 0.0f)); do_fullscreen_quad(gBlurXDecl, to_vec2(bl->size)); // blur y gpu::SetRenderTarget(bl->blur_y); gpu::SetViewport(ivec2(), bl->size, vec2(0.0f, 1.0f)); gpu::SetTexture(0, bl->blur_x); gpu::SetSampler(0, true, true); gpu::SetPsConst(0, vec4(1.0f / to_vec2(bl->size), 0.0f, 0.0f)); do_fullscreen_quad(gBlurYDecl, to_vec2(bl->size)); } // combine gpu::SetDefaultRenderTarget(); gpu::SetViewport(ivec2(0, 0), g_WinSize, vec2(0.0f, 1.0f)); gpu::SetPsConst(0, g_render_rand.v4rand(vec4(500.0f), vec4(1500.0f))); gpu::SetTexture(0, g_draw_target); gpu::SetSampler(0, true, false); for(int i = 0; i < MAX_BLOOM_LEVELS; i++) { gpu::SetTexture(1 + i, g_bloom_levels[i].blur_y); gpu::SetSampler(1 + i, true, true); } do_fullscreen_quad(gCombineDecl, to_vec2(g_WinSize)); }
CanvasProcessor::CanvasProcessor() : Processor() , inport_("inport") , dimensions_("dimensions", "Canvas Size", ivec2(256, 256), ivec2(128, 128), ivec2(4096, 4096), ivec2(1, 1), InvalidationLevel::Valid) , enableCustomInputDimensions_("enableCustomInputDimensions", "Separate Image Size", false, InvalidationLevel::Valid) , customInputDimensions_("customInputDimensions", "Image Size", ivec2(256, 256), ivec2(128, 128), ivec2(4096, 4096), ivec2(1, 1), InvalidationLevel::Valid) , keepAspectRatio_("keepAspectRatio", "Lock Aspect Ratio", true, InvalidationLevel::Valid) , aspectRatioScaling_("aspectRatioScaling", "Image Scale", 1.f, 0.1f, 4.f, 0.01f, InvalidationLevel::Valid) , visibleLayer_("visibleLayer", "Visible Layer") , colorLayer_("colorLayer_", "Color Layer ID", 0, 0, 0) , saveLayerDirectory_("layerDir", "Output Directory", "", "image") , saveLayerButton_("saveLayer", "Save Image Layer", InvalidationLevel::Valid) , inputSize_("inputSize", "Input Dimension Parameters") , toggleFullscreen_("toggleFullscreen", "Toggle Full Screen") , fullscreen_("fullscreen", "FullScreen", [this](Event* event) { setFullScreen(!isFullScreen()); }, IvwKey::F, KeyState::Press, KeyModifier::Shift) , previousImageSize_(customInputDimensions_) , widgetMetaData_{createMetaData<ProcessorWidgetMetaData>( ProcessorWidgetMetaData::CLASS_IDENTIFIER)} , canvasWidget_(nullptr) , queuedRequest_(false) { widgetMetaData_->addObserver(this); addPort(inport_); addProperty(inputSize_); dimensions_.setSerializationMode(PropertySerializationMode::None); dimensions_.onChange([this](){widgetMetaData_->setDimensions(dimensions_.get());}); inputSize_.addProperty(dimensions_); enableCustomInputDimensions_.onChange(this, &CanvasProcessor::sizeChanged); inputSize_.addProperty(enableCustomInputDimensions_); customInputDimensions_.onChange(this, &CanvasProcessor::sizeChanged); customInputDimensions_.setVisible(false); inputSize_.addProperty(customInputDimensions_); keepAspectRatio_.onChange(this, &CanvasProcessor::sizeChanged); keepAspectRatio_.setVisible(false); inputSize_.addProperty(keepAspectRatio_); aspectRatioScaling_.onChange(this, &CanvasProcessor::sizeChanged); aspectRatioScaling_.setVisible(false); inputSize_.addProperty(aspectRatioScaling_); visibleLayer_.addOption("color", "Color layer", LayerType::Color); visibleLayer_.addOption("depth", "Depth layer", LayerType::Depth); visibleLayer_.addOption("picking", "Picking layer", LayerType::Picking); visibleLayer_.set(LayerType::Color); addProperty(visibleLayer_); addProperty(colorLayer_); addProperty(saveLayerDirectory_); saveLayerButton_.onChange(this, &CanvasProcessor::saveImageLayer); addProperty(saveLayerButton_); colorLayer_.setSerializationMode(PropertySerializationMode::All); colorLayer_.setVisible(false); visibleLayer_.onChange([&]() { if (inport_.hasData()) { auto layers = inport_.getData()->getNumberOfColorLayers(); colorLayer_.setVisible(layers > 1 && visibleLayer_.get() == LayerType::Color); } }); toggleFullscreen_.onChange([this]() { setFullScreen(!isFullScreen()); }); addProperty(toggleFullscreen_); addProperty(fullscreen_); inport_.onChange([&]() { int layers = static_cast<int>(inport_.getData()->getNumberOfColorLayers()); colorLayer_.setVisible(layers > 1 && visibleLayer_.get() == LayerType::Color); colorLayer_.setMaxValue(layers - 1); }); inport_.onConnect([&](){ sizeChanged(); }); setAllPropertiesCurrentStateAsDefault(); }
void CanvasQt::touchEvent(QTouchEvent* touch) { size_t nTouchPoints = touch->touchPoints().size(); if (nTouchPoints < 1) { return; } QTouchEvent::TouchPoint firstPoint = touch->touchPoints()[0]; switch (firstPoint.state()) { case Qt::TouchPointPressed: gestureMode_ = nTouchPoints > 1; // Treat single touch point as mouse event break; case Qt::TouchPointMoved: gestureMode_ = nTouchPoints > 1; // Treat single touch point as mouse event break; case Qt::TouchPointStationary: gestureMode_ = nTouchPoints > 1; // Treat single touch point as mouse event break; case Qt::TouchPointReleased: gestureMode_ = false; break; default: gestureMode_ = false; } // Copy touch points std::vector<TouchPoint> touchPoints; touchPoints.reserve(touch->touchPoints().size()); // Fetch layer before loop (optimization) const LayerRAM* depthLayerRAM = getDepthLayerRAM(); vec2 screenSize(getScreenDimensions()); std::vector<int> endedTouchIds; for (auto& touchPoint : touch->touchPoints()) { vec2 screenTouchPos(touchPoint.pos().x(), touchPoint.pos().y()); vec2 prevScreenTouchPos(touchPoint.lastPos().x(), touchPoint.lastPos().y()); TouchPoint::TouchState touchState; switch (touchPoint.state()) { case Qt::TouchPointPressed: touchState = TouchPoint::TOUCH_STATE_STARTED; break; case Qt::TouchPointMoved: touchState = TouchPoint::TOUCH_STATE_UPDATED; break; case Qt::TouchPointStationary: touchState = TouchPoint::TOUCH_STATE_STATIONARY; break; case Qt::TouchPointReleased: touchState = TouchPoint::TOUCH_STATE_ENDED; break; default: touchState = TouchPoint::TOUCH_STATE_NONE; } ivec2 pixelCoord = ivec2(static_cast<int>(screenTouchPos.x), screenSize.y - 1 - static_cast<int>(screenTouchPos.y)); // Note that screenTouchPos/prevScreenTouchPos are in [0 screenDim] and does not need to be // adjusted to become centered in the pixel (+0.5) // Saving id order to preserve order of touch points at next touch event const auto lastIdIdx = std::find(lastTouchIds_.begin(), lastTouchIds_.end(), touchPoint.id()); if (lastIdIdx != lastTouchIds_.end()) { if (touchState == TouchPoint::TOUCH_STATE_ENDED){ endedTouchIds.push_back(touchPoint.id()); } } else{ lastTouchIds_.push_back(touchPoint.id()); } touchPoints.emplace_back(touchPoint.id(), screenTouchPos, (screenTouchPos) / screenSize, prevScreenTouchPos, (prevScreenTouchPos) / screenSize, touchState, getDepthValueAtCoord(pixelCoord, depthLayerRAM)); } // Ensure that the order to the touch points are the same as last touch event. // Note that the ID of a touch point is always the same but the order in which // they are given can vary. // Example // lastTouchIds_ touchPoints // 0 0 // 3 1 // 2 2 // 4 // Will result in: // touchPoints // 0 (no swap) // 2 (2 will swap with 1) // 1 auto touchIndex = 0; // Index to first unsorted element in touchPoints array for (const auto& lastTouchPointId : lastTouchIds_) { const auto touchPointIt = std::find_if(touchPoints.begin(), touchPoints.end(), [lastTouchPointId](const TouchPoint& p) { return p.getId() == lastTouchPointId; }); // Swap current location in the container with the location it was in last touch event. if (touchPointIt != touchPoints.end() && std::distance(touchPoints.begin(), touchPointIt) != touchIndex) { std::swap(*(touchPoints.begin() + touchIndex), *touchPointIt); ++touchIndex; } } for (auto& endedId : endedTouchIds) { std::vector<int>::iterator foundIdx = std::find(lastTouchIds_.begin(), lastTouchIds_.end(), endedId); if (foundIdx != lastTouchIds_.end()) lastTouchIds_.erase(foundIdx); } TouchEvent touchEvent(touchPoints, getScreenDimensions()); touch->accept(); // We need to send out touch event all the time to support one -> two finger touch switch Canvas::touchEvent(&touchEvent); // Mouse events will be triggered for touch events by Qt4 and Qt >= 5.3.0 // https://bugreports.qt.io/browse/QTBUG-40038 #if defined(USING_QT5) && (QT_VERSION < QT_VERSION_CHECK(5, 3, 0)) if(touch->touchPoints().size() == 1 && lastNumFingers_ < 2){ MouseEvent* mouseEvent = nullptr; ivec2 pos = ivec2(static_cast<int>(firstPoint.pos().x()), static_cast<int>(firstPoint.pos().y())); uvec2 screenPosInvY(static_cast<unsigned int>(pos.x), static_cast<unsigned int>(getScreenDimensions().y-1-pos.y)); double depth = getDepthValueAtCoord(screenPosInvY); switch (touchPoints.front().state()) { case TouchPoint::TOUCH_STATE_STARTED: mouseEvent = new MouseEvent(pos, MouseEvent::MOUSE_BUTTON_LEFT, MouseEvent::MOUSE_STATE_PRESS, EventConverterQt::getModifier(touch), getScreenDimensions(), depth); Canvas::mousePressEvent(mouseEvent); break; case TouchPoint::TOUCH_STATE_UPDATED: mouseEvent = new MouseEvent(pos, MouseEvent::MOUSE_BUTTON_LEFT, MouseEvent::MOUSE_STATE_MOVE, EventConverterQt::getModifier(touch), getScreenDimensions(), depth); Canvas::mouseMoveEvent(mouseEvent); break; case TouchPoint::TOUCH_STATE_STATIONARY: break; // Do not fire event while standing still. case TouchPoint::TOUCH_STATE_ENDED: mouseEvent = new MouseEvent(pos, MouseEvent::MOUSE_BUTTON_LEFT, MouseEvent::MOUSE_STATE_RELEASE, EventConverterQt::getModifier(touch), getScreenDimensions(), depth); Canvas::mouseReleaseEvent(mouseEvent); break; default: break; } delete mouseEvent; } #endif lastNumFingers_ = static_cast<int>(touch->touchPoints().size()); screenPositionNormalized_ = touchEvent.getCenterPointNormalized(); }
void threshold( const ChannelT<T> &srcChannel, T value, ChannelT<T> *dstChannel ) { thresholdImpl( srcChannel, value, srcChannel.getBounds(), ivec2(), dstChannel ); }
CanvasProcessor::CanvasProcessor() : Processor() , inport_("inport") , dimensions_("dimensions", "Canvas Size", ivec2(256, 256), ivec2(128, 128), ivec2(4096, 4096), ivec2(1, 1), VALID) , enableCustomInputDimensions_("enableCustomInputDimensions", "Separate Image Size", false, VALID) , customInputDimensions_("customInputDimensions", "Image Size", ivec2(256, 256), ivec2(128, 128), ivec2(4096, 4096), ivec2(1, 1), VALID) , keepAspectRatio_("keepAspectRatio", "Lock Aspect Ratio", true, VALID) , aspectRatioScaling_("aspectRatioScaling", "Image Scale", 1.f, 0.1f, 4.f, 0.01f, VALID) , visibleLayer_("visibleLayer", "Visible Layer") , colorLayer_("colorLayer_", "Color Layer ID", 0, 0, 0) , saveLayerDirectory_("layerDir", "Output Directory", "", "image") , saveLayerButton_("saveLayer", "Save Image Layer", VALID) , inputSize_("inputSize", "Input Dimension Parameters") , previousImageSize_(customInputDimensions_) , evaluator_(nullptr) , canvasWidget_(nullptr) , queuedRequest_(false) { addPort(inport_); addProperty(inputSize_); dimensions_.onChange(this, &CanvasProcessor::resizeCanvas); inputSize_.addProperty(dimensions_); enableCustomInputDimensions_.onChange(this, &CanvasProcessor::sizeChanged); inputSize_.addProperty(enableCustomInputDimensions_); customInputDimensions_.onChange(this, &CanvasProcessor::sizeChanged); customInputDimensions_.setVisible(false); inputSize_.addProperty(customInputDimensions_); keepAspectRatio_.onChange(this, &CanvasProcessor::sizeChanged); keepAspectRatio_.setVisible(false); inputSize_.addProperty(keepAspectRatio_); aspectRatioScaling_.onChange(this, &CanvasProcessor::sizeChanged); aspectRatioScaling_.setVisible(false); inputSize_.addProperty(aspectRatioScaling_); visibleLayer_.addOption("color", "Color layer", LayerType::Color); visibleLayer_.addOption("depth", "Depth layer", LayerType::Depth); visibleLayer_.addOption("picking", "Picking layer", LayerType::Picking); visibleLayer_.set(LayerType::Color); addProperty(visibleLayer_); addProperty(colorLayer_); addProperty(saveLayerDirectory_); saveLayerButton_.onChange(this, &CanvasProcessor::saveImageLayer); addProperty(saveLayerButton_); colorLayer_.setSerializationMode(PropertySerializationMode::ALL); visibleLayer_.onChange([&](){ if (inport_.hasData()){ auto layers = inport_.getData()->getNumberOfColorLayers(); colorLayer_.setVisible(layers > 1 && visibleLayer_.get() == LayerType::Color); } colorLayer_.setVisible(visibleLayer_.get() == LayerType::Color); }); inport_.onChange([&](){ int layers = static_cast<int>(inport_.getData()->getNumberOfColorLayers()); colorLayer_.setVisible(layers > 1 && visibleLayer_.get() == LayerType::Color); colorLayer_.setMaxValue(layers - 1); }); setAllPropertiesCurrentStateAsDefault(); }
geom::rect geom::circle::bounding_rect() const { const coord_t r = static_cast<coord_t>(radius); return geom::rect(origin - vec2(r, r), ivec2(radius * 2, radius * 2)); }
ivec2 Graph::preferredSize(NVGcontext *) const { return ivec2(180, 45); }
hexmap_t::hexmap_t() : map_data(ivec2(15, 16)) { }
void ImageResample::dimensionChanged() { if (dimensions_.get() != ivec2(outport_.getDimensions())) { outport_.setDimensions(dimensions_.get()); internalInvalid_ = true; } }
Quad(float width, float height) : m_size(width, height) { ParametricInterval interval = { ivec2(2, 2), vec2(1, 1), vec2(1, 1) }; SetInterval(interval); }
// // NON-Feature // void placeNonFeaturePatches(const Heightmap *source, const Heightmap *target, Heightmap *output, int patch_size) { ppa::RidgeGraph source_ridges = ppa::ppa_Tasse(source); vector<ppa::vertex> source_points = getSpacedVerticies(source_ridges, patch_size / 2); Array<bool> feature_mask(source->size(), false); Array<bool> feature_patch(patch_size *1, patch_size * 1, true); // Blot out feature mask (with a buffer) for (ppa::vertex v : source_points) { feature_mask.block(feature_patch, v.p - (patch_size)); } // create a list of all candidates (non-feature patches) // Iterate over feature mask vector<Patch> candidates; for (int y = patch_size/2; y < source->height() - patch_size/2; ++y) { for (int x = patch_size/2; x < source->width() - patch_size/2; ++x) { ivec2 p(x, y); // If this position is not a feature if (!feature_mask.at(p)) { // Add to candidates candidates.emplace_back(Patch(*source, ivec2(p - patch_size / 2), patch_size)); feature_mask.block(feature_patch, p - (patch_size / 2)); } //if (candidates.size() > 100) break; } //if (candidates.size() > 100) break; } // TODO flip // TODO rotate // ALL patches // for every point that does not have a value for (int y = 0; y < output->height(); ++y) { for (int x = 0; x < output->width(); ++x) { if (!output->isnan(x, y)) continue; ivec2 p(x, y); static int asd = 0; //if (++asd>100) return; // stop after x amount; // // Get Target Patch ivec2 target_offset(p - patch_size / 2); Patch target_patch(*output, target_offset, patch_size); Heightmap best_patch = bestPatch(output, target_patch, target_offset, candidates); mergePatch(output, &best_patch, target_offset); } } }
TrefoilKnot(float scale) : m_scale(scale) { ParametricInterval interval = { ivec2(60, 15), vec2(TwoPi, TwoPi), vec2(100, 8) }; SetInterval(interval); }
void net_reload() { if (prot) { if (net_server) { if (current_level) delete current_level; bFILE *fp; if (!reload_start()) return ; do { // make sure server saves the file fp=open_file(NET_STARTFILE,"rb"); if (fp->open_failure()) { delete fp; fp=NULL; } } while (!fp); spec_directory sd(fp); #if 0 spec_entry *e=sd.find("Copyright 1995 Crack dot Com, All Rights reserved"); if (!e) { the_game->show_help("This level is missing copyright information, cannot load\n"); current_level=new level(100,100,"untitled"); the_game->need_refresh(); } else #endif current_level=new level(&sd,fp,NET_STARTFILE); delete fp; base->current_tick=(current_level->tick_counter()&0xff); reload_end(); } else if (current_level) { join_struct *join_list=base->join_list; while (join_list) { view *f=player_list; for (; f && f->next; f=f->next); // find last player, add one for pn int i,st=0; for (i=0; i<total_objects; i++) if (!strcmp(object_names[i],"START")) st=i; game_object *o=create(current_start_type,0,0); game_object *start=current_level->get_random_start(320,NULL); if (start) { o->x=start->x; o->y=start->y; } else { o->x=100; o->y=100; } f->next=new view(o,NULL,join_list->client_id); strncpy(f->next->name,join_list->name, view::namesize); o->set_controller(f->next); f->next->set_tint(f->next->player_number); if (start) current_level->add_object_after(o,start); else current_level->add_object(o); view *v = f->next; v->m_aa = ivec2(5); v->m_bb = ivec2(319, 199) - ivec2(5); join_list = join_list->next; } base->join_list=NULL; current_level->save(NET_STARTFILE,1); base->mem_lock=0; Jwindow *j=wm->CreateWindow(ivec2(0, yres / 2), ivec2(-1), new info_field(0, 0, 0, symbol_str("resync"), new button(0, wm->font()->Size().y + 5, ID_NET_DISCONNECT, symbol_str("slack"),NULL)),symbol_str("hold!")) ; wm->flush_screen(); if (!reload_start()) return ; base->input_state=INPUT_RELOAD; // if someone missed the game tick with the RELOAD data in it, make sure the get it // wait for all client to reload the level with the new players do { service_net_request(); if (wm->IsPending()) { Event ev; do { wm->get_event(ev); if (ev.type==EV_MESSAGE && ev.message.id==ID_NET_DISCONNECT) { game_face->end_reload(1); base->input_state=INPUT_PROCESSING; } } while (wm->IsPending()); wm->flush_screen(); } } while (!reload_end()); wm->close_window(j); unlink(NET_STARTFILE); the_game->reset_keymap(); base->input_state=INPUT_COLLECTING; } } }
KleinBottle(float scale) : m_scale(scale) { ParametricInterval interval = { ivec2(20, 20), vec2(TwoPi, TwoPi), vec2(15, 50) }; SetInterval(interval); }
int get_inputs_from_server(unsigned char *buf) { if (prot && base->input_state!=INPUT_PROCESSING) // if input is not here, wait on it { time_marker start; int total_retry=0; Jwindow *abort=NULL; while (base->input_state!=INPUT_PROCESSING) { if (!prot) { base->input_state=INPUT_PROCESSING; return 1; } service_net_request(); time_marker now; // if this is taking to long, the packet was probably lost, ask for it to be resent if (now.diff_time(&start)>0.05) { if (prot->debug_level(net_protocol::DB_IMPORTANT_EVENT)) fprintf(stderr,"(missed packet)"); game_face->input_missing(); start.get_time(); total_retry++; if (total_retry==12000) // 2 minutes and nothing { abort=wm->CreateWindow(ivec2(0, yres / 2), ivec2(-1, wm->font()->Size().y*4), new info_field(0, 0, 0, symbol_str("waiting"), new button(0, wm->font()->Size().y + 5, ID_NET_DISCONNECT, symbol_str("slack"),NULL)),symbol_str("Error")); wm->flush_screen(); } } if (abort) { if (wm->IsPending()) { Event ev; do { wm->get_event(ev); if (ev.type==EV_MESSAGE && ev.message.id==ID_NET_DISCONNECT) { kill_slackers(); base->input_state=INPUT_PROCESSING; } } while (wm->IsPending()); wm->flush_screen(); } } } if (abort) { wm->close_window(abort); the_game->reset_keymap(); } } memcpy(base->last_packet.data,base->packet.data,base->packet.packet_size()+base->packet.packet_prefix_size()); int size=base->packet.packet_size(); memcpy(buf,base->packet.packet_data(),size); base->packet.packet_reset(); base->mem_lock=0; return size; }
void Recti::set(int x, int y, int width, int height) { position = ivec2(x, y); size = ivec2(width, height); }
void threshold( const SurfaceT<T> &surface, T value, SurfaceT<T> *dstSurface ) { thresholdImpl( surface, value, surface.getBounds(), ivec2(), dstSurface ); }
void CanvasProcessorWidgetQt::moveEvent(QMoveEvent* event) { CanvasProcessorWidget::setPosition(ivec2(event->pos().x(), event->pos().y())); QWidget::moveEvent(event); }
/** * Helper to keep track of the mouse. Mainly used to have an optional GLUTMouse updated. */ void GLUTCanvas::keepMouseUpdated(const int& x, const int& y) { if (glutMouse_) glutMouse_->setPosition(ivec2(x, y)); }