void kepler_elements_from_state( double mu, const double *pos, const double *vel, double epoch, struct kepler_elements *elements) { double r = mag(pos); double v2 = dot(vel, vel); // specific angular momentum double h[3]; cross(pos, vel, h); // TODO: check for radial trajectory // eccentricity vector, direction: to periapsis, magnitude: eccentricity // e = 1/mu * (v^2 - mu/r) * r - dot(r, v) * v; double ecc[3]; for(int i = 0; i < 3; ++i) ecc[i] = (1.0 / mu) * (pos[i]*(v2 - mu/r) - vel[i]*dot(pos, vel)); double e = mag(ecc); bool circular = zero(e); bool parabolic = zero(e - 1.0); // line of nodes, pointing to ascending node, equatorial -> zero double nodes[3] = { -h[1], h[0], 0.0 }; double N = mag(nodes); bool equatorial = zero(dot(nodes, nodes)); // semi-latus rectum double p = dot(h, h) / mu; // inclination double i = acos(clamp(-1.0, 1.0, h[2] / mag(h))); // longitude of ascending node double an = equatorial ? 0.0 : atan2(nodes[1], nodes[0]); // argument of periapsis double arg = 0.0 / 0.0; // NaN if(circular) // circular, zero arg = 0.0; else if(equatorial) // equatorial, measure from X-axis, negative for retrograde arg = sign(h[2]) * atan2(ecc[1], ecc[0]); else // angle between eccentricity vector and line of nodes (ascending node) arg = sign(ecc[2]) * acos(clamp(-1.0, 1.0, dot(nodes, ecc) / (N * e))); // true anomaly double f = 0.0 / 0.0; // NaN if(circular && equatorial) // circular, equatorial -> measure from X-axis, negative for retrograde f = sign(h[2]) * atan2(pos[1], pos[0]); else if(circular) // circular orbit -> measure from ascending node f = -sign(dot(vel, nodes)) * acos(clamp(-1.0, 1.0, dot(nodes, pos) / (N * r))); else // measure true anomaly from periapsis (eccentricity vector) f = -sign(dot(vel, ecc)) * acos(clamp(-1.0, 1.0, dot(ecc, pos) / (e * r))); // mean anomaly at epoch double M0 = kepler_anomaly_true_to_mean(e, f); // mean motion double a = p / (1.0 - e*e); double n = parabolic ? sqrt(mu / (p*p*p)) : sqrt(mu / fabs(a*a*a)); // time at periapsis double periapsis_time = epoch - M0 / n; elements->semi_latus_rectum = p; elements->eccentricity = e; elements->mean_motion = n; elements->inclination = i; elements->longitude_of_ascending_node = an; elements->argument_of_periapsis = arg; elements->periapsis_time = periapsis_time; }
X264Encoder(int fps, int width, int height, int quality, CTSTR preset, CTSTR ProFile, bool bUse444, ColorDescription &colorDesc, int maxBitrate, int bufferSize, bool bUseCFR, bool bUesBackConfig) { frameShift = 0; curPreset = preset; FPS = fps; fps_ms = 1000 / fps; StringList paramList; curProfile = ProFile; zero(¶mData, sizeof(paramData)); LPSTR lpPreset = curPreset.CreateUTF8String(); LPSTR lpTune = curTune.CreateUTF8String(); if (x264_param_default_preset(¶mData, lpPreset, lpTune)) Log::writeError(LOG_RTSPSERV,1,"LiveSDK_Log:Failed to set x264 defaults: %s/%s", curPreset.Array(), curTune.Array()); Free(lpTune); Free(lpPreset); this->width = width; this->height = height; paramData.b_deterministic = false; //分主次直播 if (bUesBackConfig) { bUseCBR = CSLiveManager::GetInstance()->BSParam.LiveSetting.bUseCBRSec; } else { bUseCBR = CSLiveManager::GetInstance()->BSParam.LiveSetting.bUseCBR; } bPadCBR = true; this->bUseCFR = bUseCFR; SetBitRateParams(maxBitrate, bufferSize); if (bUseCBR) { if (bPadCBR) paramData.rc.b_filler = 1; //if(bPadCBR) paramData.i_nal_hrd = X264_NAL_HRD_CBR; paramData.rc.i_rc_method = X264_RC_ABR; paramData.rc.f_rf_constant = 0.0f; } else { paramData.i_frame_reference = 5; paramData.rc.i_rc_method = X264_RC_CRF; paramData.rc.f_rf_constant = baseCRF + float(10 - quality); } //分主次直播 UINT keyframeInterval = CSLiveManager::GetInstance()->BSParam.LiveSetting.KeyFrame; if (bUesBackConfig) { keyframeInterval = CSLiveManager::GetInstance()->BSParam.LiveSetting.KeyFrameSec; } paramData.b_vfr_input = !bUseCFR; paramData.i_width = width; paramData.i_height = height; paramData.vui.b_fullrange = colorDesc.fullRange; paramData.vui.i_colorprim = colorDesc.primaries; paramData.vui.i_transfer = colorDesc.transfer; paramData.vui.i_colmatrix = colorDesc.matrix; if (keyframeInterval) paramData.i_keyint_max = fps*keyframeInterval; paramData.i_fps_num = fps; paramData.i_fps_den = 1; paramData.i_timebase_num = 1; paramData.i_timebase_den = 1000; paramData.pf_log = get_x264_log; paramData.i_log_level = X264_LOG_WARNING; //分主次直播 int nBFrameCount = CSLiveManager::GetInstance()->BSParam.LiveSetting.BFrameCount; if (bUesBackConfig) { nBFrameCount = CSLiveManager::GetInstance()->BSParam.LiveSetting.BFrameCountSec; } if (-1 != nBFrameCount) { paramData.i_bframe = nBFrameCount; } //录制高品质不能播放 paramData.b_vfr_input = 0; if (0 == nBFrameCount) { // http://bbs.csdn.net/topics/390922653 paramData.rc.i_lookahead = 0; paramData.i_sync_lookahead = 0; paramData.i_bframe = 0; paramData.b_sliced_threads = 1; paramData.rc.b_mb_tree = 0; } if (scmpi(curProfile, L"main") == 0) paramData.i_level_idc = 41; // to ensure compatibility with portable devices for (UINT i = 0; i<paramList.Num(); i++) { String &strParam = paramList[i]; if (!schr(strParam, '=')) continue; String strParamName = strParam.GetToken(0, '='); String strParamVal = strParam.GetTokenOffset(1, '='); if (strParamName.CompareI(TEXT("fps")) || strParamName.CompareI(TEXT("force-cfr"))) { Log(TEXT("The custom x264 command '%s' is unsupported, use the application settings instead"), strParam.Array()); continue; } else { LPSTR lpParam = strParamName.CreateUTF8String(); LPSTR lpVal = strParamVal.CreateUTF8String(); if (x264_param_parse(¶mData, lpParam, lpVal) != 0) Log(TEXT("The custom x264 command '%s' failed"), strParam.Array()); Free(lpParam); Free(lpVal); } } if (bUse444) paramData.i_csp = X264_CSP_I444; else paramData.i_csp = X264_CSP_I420; colorDesc.fullRange = paramData.vui.b_fullrange; colorDesc.primaries = paramData.vui.i_colorprim; colorDesc.transfer = paramData.vui.i_transfer; colorDesc.matrix = paramData.vui.i_colmatrix; if (curProfile) { LPSTR lpProfile = curProfile.CreateUTF8String(); if (x264_param_apply_profile(¶mData, lpProfile)) Log::writeMessage(LOG_RTSPSERV,1,"LiveSDK_Log:Failed to set x264 profile: %s", curProfile.Array()); Free(lpProfile); } }
// this is able to handle multiple weapon graphics now // removed mountRotation,they get such stuff from psObj directly now static void displayCompObj(DROID *psDroid, bool bButton) { iIMDShape *psShape, *psJet, *psShapeTemp = NULL, *psMountShape; Vector3i zero(0, 0, 0); Vector2i screenCoords; SDWORD iConnector; PROPULSION_STATS *psPropStats; SDWORD frame; SDWORD pieFlag, iPieData; PIELIGHT brightness; UDWORD colour; UBYTE i; if( (gameTime-psDroid->timeLastHit < GAME_TICKS_PER_SEC/4 ) && psDroid->lastHitWeapon == WSC_ELECTRONIC && !gamePaused()) { colour = getPlayerColour(rand()%MAX_PLAYERS); } else { colour = getPlayerColour(psDroid->player); } /* get propulsion stats */ psPropStats = asPropulsionStats + psDroid->asBits[COMP_PROPULSION].nStat; ASSERT_OR_RETURN( , psPropStats != NULL, "invalid propulsion stats pointer"); //set pieflag for button object or ingame object if ( bButton ) { pieFlag = pie_BUTTON; } else { pieFlag = 0; } if(!bButton) { brightness = pal_SetBrightness(psDroid->illumination); pieFlag = pie_SHADOW; } else { brightness = WZCOL_WHITE; } /* set default components transparent */ if ( psDroid->asBits[COMP_PROPULSION].nStat == 0 ) { pieFlag |= pie_TRANSLUCENT; iPieData = DEFAULT_COMPONENT_TRANSLUCENCY; } else { iPieData = 0; } if (!bButton && psPropStats->propulsionType == PROPULSION_TYPE_PROPELLOR) { // FIXME: change when adding submarines to the game pie_TRANSLATE(0, -world_coord(1)/2.3f, 0); } //uses psShapeTemp too separate it from turret's psShape psShapeTemp = (leftFirst ? getLeftPropulsionIMD(psDroid) : getRightPropulsionIMD(psDroid)); if(psShapeTemp!=NULL) { pie_Draw3DShape(psShapeTemp, 0, colour, brightness, pieFlag, iPieData); } /* set default components transparent */ if ( psDroid->asBits[COMP_BODY].nStat == 0 ) { pieFlag |= pie_TRANSLUCENT; iPieData = DEFAULT_COMPONENT_TRANSLUCENCY; } else { pieFlag &= ~pie_TRANSLUCENT; iPieData = 0; } /* Get the body graphic now*/ //uses psShapeTemp too separate it from turret's psShape psShapeTemp = BODY_IMD(psDroid,psDroid->player); if(psShapeTemp!=NULL) { // FIXME if ( psDroid->droidType == DROID_PERSON) { /* draw body if not animating */ if ( psDroid->psCurAnim == NULL || psDroid->psCurAnim->bVisible == false ) { // FIXME - hideous....!!!! pie_MatScale(.75f); pie_Draw3DShape(psShapeTemp, 0, psDroid->player-6, brightness, pieFlag, iPieData); } } else if (cyborgDroid(psDroid)) { /* draw body if cyborg not animating */ if ( psDroid->psCurAnim == NULL || psDroid->psCurAnim->bVisible == false ) { pie_Draw3DShape(psShapeTemp, 0, colour, brightness, pieFlag, iPieData); } } else { pie_Draw3DShape(psShapeTemp, 0, colour, brightness, pieFlag, iPieData); } } /* render vtol jet if flying - horrible hack - GJ */ if (((psPropStats->propulsionType == PROPULSION_TYPE_LIFT) && //(psDroid->droidType != DROID_CYBORG)) && (!bButton)) (!cyborgDroid(psDroid))) && (!bButton)) { /* show flame if above ground */ if ( psDroid->sMove.Status != MOVEINACTIVE ) { /* draw flame if found */ /* GJ TODO: add flame-finding code here */ psJet = asBodyStats[psDroid->asBits[COMP_BODY].nStat].pFlameIMD; if ( psJet != NULL ) { pie_Draw3DShape(psJet, getModularScaledGraphicsTime(100, psJet->numFrames), colour, brightness, pie_ADDITIVE, 200); } } } //don't change the screen coords of an object if drawing it in a button if (!bButton) { /* set up all the screen coords stuff - need to REMOVE FROM THIS LOOP */ calcScreenCoords(psDroid); } /* set default components transparent */ if (psDroid->asWeaps[0].nStat == 0 && psDroid->asBits[COMP_SENSOR].nStat == 0 && psDroid->asBits[COMP_ECM].nStat == 0 && psDroid->asBits[COMP_BRAIN].nStat == 0 && psDroid->asBits[COMP_REPAIRUNIT].nStat == 0 && psDroid->asBits[COMP_CONSTRUCT].nStat == 0) { pieFlag |= pie_TRANSLUCENT; iPieData = DEFAULT_COMPONENT_TRANSLUCENCY; } else { pieFlag &= ~pie_TRANSLUCENT; iPieData = 0; } /* Indenting here is only to show new matrix context */ { psShapeTemp = BODY_IMD(psDroid,psDroid->player); if( psShapeTemp->nconnectors ) { /* vtol weapons attach to connector 2 (underneath); * all others to connector 1 */ /* VTOL's now skip the first 5 connectors(0 to 4), VTOL's use 5,6,7,8 etc now */ if ( (psPropStats->propulsionType == PROPULSION_TYPE_LIFT) && psDroid->droidType == DROID_WEAPON ) { iConnector = VTOL_CONNECTOR_START; } else { iConnector = 0; } switch(psDroid->droidType) { case DROID_DEFAULT: case DROID_TRANSPORTER: case DROID_CYBORG: case DROID_CYBORG_SUPER: case DROID_WEAPON: case DROID_COMMAND: // command droids have a weapon to store all the graphics /* Get the mounting graphic - we've already moved to the right position Allegedly - all droids will have a mount graphic so this shouldn't fall on it's arse......*/ /* Double check that the weapon droid actually has any */ for (i = 0;i < psDroid->numWeaps;i++) { if (psDroid->asWeaps[i].nStat > 0 || psDroid->droidType == DROID_DEFAULT) { if ( psShapeTemp->connectors ) { Rotation rot = getInterpolatedWeaponRotation(psDroid, i, graphicsTime); pie_MatBegin(); //to skip number of VTOL_CONNECTOR_START ground unit connectors if ( iConnector < VTOL_CONNECTOR_START ) { pie_TRANSLATE(psShapeTemp->connectors[i].x, psShapeTemp->connectors[i].z, psShapeTemp->connectors[i].y); } else { pie_TRANSLATE( psShapeTemp->connectors[iConnector + i].x, psShapeTemp->connectors[iConnector + i].z, psShapeTemp->connectors[iConnector + i].y ); } pie_MatRotY(-rot.direction); /* vtol weapons inverted */ if ( iConnector >= VTOL_CONNECTOR_START ) { pie_MatRotZ(65536/2); //this might affect gun rotation } /* Get the mount graphic */ psShape = WEAPON_MOUNT_IMD(psDroid, i); pie_TRANSLATE(0,0,psDroid->asWeaps[i].recoilValue/3); /* Draw it */ if(psShape) { pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData); } pie_TRANSLATE(0,0,psDroid->asWeaps[i].recoilValue); /* translate for weapon mount point */ if (psShape && psShape->nconnectors) { pie_TRANSLATE(psShape->connectors->x, psShape->connectors->z, psShape->connectors->y); } /* vtol weapons inverted */ if ( iConnector >= VTOL_CONNECTOR_START ) { //pitch the barrel down pie_MatRotX(-rot.pitch); } else { //pitch the barrel up pie_MatRotX(rot.pitch); } /* Get the weapon (gun?) graphic */ psShape = WEAPON_IMD(psDroid, i); // We have a weapon so we draw it and a muzzle flash from weapon connector if (psShape) { pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData); if (psShape->nconnectors) { unsigned int connector_num = 0; // which barrel is firing if model have multiple muzzle connectors? if (psDroid->asWeaps[i].shotsFired && (psShape->nconnectors > 1)) { // shoot first, draw later - substract one shot to get correct results connector_num = (psDroid->asWeaps[i].shotsFired - 1) % (psShape->nconnectors); } /* Now we need to move to the end of the firing barrel (there maybe multiple barrels) */ pie_TRANSLATE( psShape->connectors[connector_num].x, psShape->connectors[connector_num].z, psShape->connectors[connector_num].y); //and draw the muzzle flash psShape = MUZZLE_FLASH_PIE(psDroid, i); if (psShape) { //assume no clan colours for muzzle effects if ((psShape->numFrames == 0) || (psShape->animInterval <= 0)) { //no anim so display one frame for a fixed time if (gameTime < (psDroid->asWeaps[i].lastFired + BASE_MUZZLE_FLASH_DURATION)) { pie_Draw3DShape(psShape, 0, 0, brightness, pieFlag | pie_ADDITIVE, EFFECT_MUZZLE_ADDITIVE); } } else { // animated muzzle frame = (gameTime - psDroid->asWeaps[i].lastFired) / psShape->animInterval; if (frame < psShape->numFrames) { pie_Draw3DShape(psShape, frame, 0, brightness, pieFlag | pie_ADDITIVE, EFFECT_MUZZLE_ADDITIVE); } } } } } } /* Pop Matrix */ pie_MatEnd(); } } break; case DROID_SENSOR: case DROID_CONSTRUCT: case DROID_CYBORG_CONSTRUCT: case DROID_ECM: case DROID_REPAIR: case DROID_CYBORG_REPAIR: { Rotation rot = getInterpolatedWeaponRotation(psDroid, 0, graphicsTime); switch (psDroid->droidType) { default: ASSERT(false, "..."); case DROID_SENSOR: psMountShape = SENSOR_MOUNT_IMD(psDroid, psDroid->player); /* Get the sensor graphic, assuming it's there */ psShape = SENSOR_IMD(psDroid, psDroid->player); break; case DROID_CONSTRUCT: case DROID_CYBORG_CONSTRUCT: psMountShape = CONSTRUCT_MOUNT_IMD(psDroid, psDroid->player); /* Get the construct graphic assuming it's there */ psShape = CONSTRUCT_IMD(psDroid, psDroid->player); break; case DROID_ECM: psMountShape = ECM_MOUNT_IMD(psDroid, psDroid->player); /* Get the ECM graphic assuming it's there.... */ psShape = ECM_IMD(psDroid, psDroid->player); break; case DROID_REPAIR: case DROID_CYBORG_REPAIR: psMountShape = REPAIR_MOUNT_IMD(psDroid, psDroid->player); /* Get the Repair graphic assuming it's there.... */ psShape = REPAIR_IMD(psDroid, psDroid->player); break; } /* Get the mounting graphic - we've already moved to the right position Allegedly - all droids will have a mount graphic so this shouldn't fall on it's arse......*/ //sensor and cyborg and ecm uses connectors[0] pie_MatBegin(); /* vtol weapons inverted */ if ( iConnector >= VTOL_CONNECTOR_START ) { pie_MatRotZ(65536/2); //this might affect gun rotation } pie_TRANSLATE( psShapeTemp->connectors[0].x, psShapeTemp->connectors[0].z, psShapeTemp->connectors[0].y ); pie_MatRotY(-rot.direction); /* Draw it */ if (psMountShape) { pie_Draw3DShape(psMountShape, 0, colour, brightness, pieFlag, iPieData); } /* translate for construct mount point if cyborg */ if (cyborgDroid(psDroid) && psMountShape && psMountShape->nconnectors) { pie_TRANSLATE(psMountShape->connectors[0].x, psMountShape->connectors[0].z, psMountShape->connectors[0].y); } /* Draw it */ if(psShape) { pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData); // In repair droid case only: if ((psDroid->droidType == DROID_REPAIR || psDroid->droidType == DROID_CYBORG_REPAIR) && psShape->nconnectors && psDroid->action == DACTION_DROIDREPAIR) { Spacetime st = interpolateObjectSpacetime(psDroid, graphicsTime); Rotation rot = getInterpolatedWeaponRotation(psDroid, 0, graphicsTime); pie_TRANSLATE( psShape->connectors[0].x, psShape->connectors[0].z, psShape->connectors[0].y ); pie_TRANSLATE(0,-20,0); psShape = getImdFromIndex(MI_FLAME); /* Rotate for droid */ pie_MatRotY(st.rot.direction); pie_MatRotX(-st.rot.pitch); pie_MatRotZ(-st.rot.roll); //rotate Y pie_MatRotY(rot.direction); pie_MatRotY(-player.r.y); pie_MatRotX(-player.r.x); pie_Draw3DShape(psShape, getModularScaledGraphicsTime(100, psShape->numFrames), 0, brightness, pie_ADDITIVE, 140); pie_MatRotX(player.r.x); pie_MatRotY(player.r.y); } } /* Pop Matrix */ pie_MatEnd(); break; } case DROID_PERSON: // no extra mounts for people break; default: ASSERT(!"invalid droid type", "Whoa! Weirdy type of droid found in drawComponentObject!!!"); break; } } /* We've also got a handle on the psShape here for the weapon which has a connector to point to muzzle flash attachment points - just grab it from psShape->connectors->[x|y|z] */ } // end of illustrative indentation - see above /* set default components transparent */ if ( psDroid->asBits[COMP_PROPULSION].nStat == 0 ) { pieFlag |= pie_TRANSLUCENT; iPieData = DEFAULT_COMPONENT_TRANSLUCENCY; } else { pieFlag &= ~pie_TRANSLUCENT; iPieData = 0; } psShape = (leftFirst ? getRightPropulsionIMD(psDroid) : getLeftPropulsionIMD(psDroid)); if(psShape!=NULL) { pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData); } }
D3D10VertexBuffer* D3D10VertexBuffer::CreateVertexBuffer(VBData *vbData, BOOL bStatic, D3D10System *D3DSystem) { if(!vbData) { AppWarning(TEXT("D3D10VertexBuffer::CreateVertexBuffer: vbData NULL")); return NULL; } HRESULT err; D3D10VertexBuffer *buf = new D3D10VertexBuffer; buf->numVerts = vbData->VertList.Num(); D3D11_BUFFER_DESC bd; D3D11_SUBRESOURCE_DATA srd; zero(&bd, sizeof(bd)); zero(&srd, sizeof(srd)); bd.Usage = bStatic ? D3D11_USAGE_DEFAULT : D3D11_USAGE_DYNAMIC; bd.CPUAccessFlags = bStatic ? 0 : D3D11_CPU_ACCESS_WRITE; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; //---------------------------------------- buf->vertexSize = sizeof(Vect); bd.ByteWidth = sizeof(Vect)*buf->numVerts; srd.pSysMem = vbData->VertList.Array(); err = D3DSystem->GetDeviceInline()->CreateBuffer(&bd, &srd, &buf->vertexBuffer); if(FAILED(err)) { AppWarning(TEXT("D3D10VertexBuffer::CreateVertexBuffer: Failed to create the vertex portion of the vertex buffer, result = %08lX"), err); delete buf; return NULL; } //---------------------------------------- if(vbData->NormalList.Num()) { buf->normalSize = sizeof(Vect); bd.ByteWidth = sizeof(Vect)*buf->numVerts; srd.pSysMem = vbData->NormalList.Array(); err = D3DSystem->GetDeviceInline()->CreateBuffer(&bd, &srd, &buf->normalBuffer); if(FAILED(err)) { AppWarning(TEXT("D3D10VertexBuffer::CreateVertexBuffer: Failed to create the normal portion of the vertex buffer, result = %08lX"), err); delete buf; return NULL; } } //---------------------------------------- if(vbData->ColorList.Num()) { buf->colorSize = sizeof(DWORD); bd.ByteWidth = sizeof(DWORD)*buf->numVerts; srd.pSysMem = vbData->ColorList.Array(); err = D3DSystem->GetDeviceInline()->CreateBuffer(&bd, &srd, &buf->colorBuffer); if(FAILED(err)) { AppWarning(TEXT("D3D10VertexBuffer::CreateVertexBuffer: Failed to create the color portion of the vertex buffer, result = %08lX"), err); delete buf; return NULL; } } //---------------------------------------- if(vbData->TangentList.Num()) { buf->tangentSize = sizeof(Vect); bd.ByteWidth = sizeof(Vect)*buf->numVerts; srd.pSysMem = vbData->TangentList.Array(); err = D3DSystem->GetDeviceInline()->CreateBuffer(&bd, &srd, &buf->tangentBuffer); if(FAILED(err)) { AppWarning(TEXT("D3D10VertexBuffer::CreateVertexBuffer: Failed to create the tangent portion of the vertex buffer, result = %08lX"), err); delete buf; return NULL; } } //---------------------------------------- if(vbData->UVList.Num()) { buf->UVBuffers.SetSize(vbData->UVList.Num()); buf->UVSizes.SetSize(vbData->UVList.Num()); for(UINT i=0; i<vbData->UVList.Num(); i++) { List<UVWCoord> &textureVerts = vbData->UVList[i]; buf->UVSizes[i] = sizeof(UVWCoord); bd.ByteWidth = buf->UVSizes[i]*buf->numVerts; srd.pSysMem = textureVerts.Array(); ID3D11Buffer *tvBuffer; err = D3DSystem->GetDeviceInline()->CreateBuffer(&bd, &srd, &tvBuffer); if(FAILED(err)) { AppWarning(TEXT("D3D10VertexBuffer::CreateVertexBuffer: Failed to create the texture vertex %d portion of the vertex buffer, result = %08lX"), i, err); delete buf; return NULL; } buf->UVBuffers[i] = tvBuffer; } } //---------------------------------------- buf->bDynamic = !bStatic; if(bStatic) { delete vbData; buf->data = NULL; } else buf->data = vbData; return buf; }
INT_PTR SettingsAdvanced::ProcMessage(UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_INITDIALOG: { LocalizeWindow(hwnd); //-------------------------------------------- HWND hwndToolTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL, WS_POPUP|TTS_NOPREFIX|TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwnd, NULL, hinstMain, NULL); TOOLINFO ti; zero(&ti, sizeof(ti)); ti.cbSize = sizeof(ti); ti.uFlags = TTF_SUBCLASS|TTF_IDISHWND; ti.hwnd = hwnd; SendMessage(hwndToolTip, TTM_SETMAXTIPWIDTH, 0, 500); SendMessage(hwndToolTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, 14000); //------------------------------------ UINT sceneBufferingTime = GlobalConfig->GetInt(TEXT("General"), TEXT("SceneBufferingTime"), 700); SendMessage(GetDlgItem(hwnd, IDC_SCENEBUFFERTIME), UDM_SETRANGE32, 60, 20000); SendMessage(GetDlgItem(hwnd, IDC_SCENEBUFFERTIME), UDM_SETPOS32, 0, sceneBufferingTime); //------------------------------------ bool bUseMTOptimizations = AppConfig->GetInt(TEXT("General"), TEXT("UseMultithreadedOptimizations"), TRUE) != 0; SendMessage(GetDlgItem(hwnd, IDC_USEMULTITHREADEDOPTIMIZATIONS), BM_SETCHECK, bUseMTOptimizations ? BST_CHECKED : BST_UNCHECKED, 0); HWND hwndTemp = GetDlgItem(hwnd, IDC_PRIORITY); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Advanced.Priority.High")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Advanced.Priority.AboveNormal")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Advanced.Priority.Normal")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Advanced.Priority.Idle")); CTSTR pStr = AppConfig->GetStringPtr(TEXT("General"), TEXT("Priority"), TEXT("Normal")); if (scmpi(pStr, TEXT("Idle")) == 0) SendMessage(hwndTemp, CB_SETCURSEL, 3, 0); else if (scmpi(pStr, TEXT("Above Normal")) == 0) SendMessage(hwndTemp, CB_SETCURSEL, 1, 0); else if (scmpi(pStr, TEXT("High")) == 0) SendMessage(hwndTemp, CB_SETCURSEL, 0, 0); else //Normal SendMessage(hwndTemp, CB_SETCURSEL, 2, 0); //------------------------------------ bool bDisablePreviewEncoding = GlobalConfig->GetInt(TEXT("General"), TEXT("DisablePreviewEncoding"), false) != 0; SendMessage(GetDlgItem(hwnd, IDC_DISABLEPREVIEWENCODING), BM_SETCHECK, bDisablePreviewEncoding ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ bool bAllowOtherHotkeyModifiers = GlobalConfig->GetInt(TEXT("General"), TEXT("AllowOtherHotkeyModifiers"), true) != 0; SendMessage(GetDlgItem(hwnd, IDC_ALLOWOTHERHOTKEYMODIFIERS), BM_SETCHECK, bAllowOtherHotkeyModifiers ? BST_CHECKED : BST_UNCHECKED, 0); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_X264PROFILE); static const CTSTR profile_names[3] = {TEXT("main"), TEXT("high")}; for(int i=0; i<2; i++) SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)profile_names[i]); LoadSettingComboString(hwndTemp, TEXT("Video Encoding"), TEXT("X264Profile"), TEXT("high")); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_PRESET); static const CTSTR preset_names[8] = {TEXT("ultrafast"), TEXT("superfast"), TEXT("veryfast"), TEXT("faster"), TEXT("fast"), TEXT("medium"), TEXT("slow"), TEXT("slower")}; for(int i=0; i<8; i++) SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)preset_names[i]); LoadSettingComboString(hwndTemp, TEXT("Video Encoding"), TEXT("Preset"), TEXT("veryfast")); ti.lpszText = (LPWSTR)Str("Settings.Advanced.VideoEncoderCPUTradeoffTooltip"); ti.uId = (UINT_PTR)hwndTemp; SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); //------------------------------------ bool bUseCFR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCFR"), 1) != 0; SendMessage(GetDlgItem(hwnd, IDC_USECFR), BM_SETCHECK, bUseCFR ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ bool bUseCustomX264Settings = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCustomSettings")) != 0; String strX264Settings = AppConfig->GetString(TEXT("Video Encoding"), TEXT("CustomSettings")); SendMessage(GetDlgItem(hwnd, IDC_USEVIDEOENCODERSETTINGS), BM_SETCHECK, bUseCustomX264Settings ? BST_CHECKED : BST_UNCHECKED, 0); SetWindowText(GetDlgItem(hwnd, IDC_VIDEOENCODERSETTINGS), strX264Settings); ti.lpszText = (LPWSTR)Str("Settings.Advanced.VideoEncoderSettingsTooltip"); ti.uId = (UINT_PTR)GetDlgItem(hwnd, IDC_VIDEOENCODERSETTINGS); SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); ti.uId = (UINT_PTR)GetDlgItem(hwnd, IDC_USEVIDEOENCODERSETTINGS); SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); EnableWindow(GetDlgItem(hwnd, IDC_VIDEOENCODERSETTINGS), bUseCustomX264Settings); //-------------------------------------------- UINT keyframeInt = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("KeyframeInterval"), 0); SendMessage(GetDlgItem(hwnd, IDC_KEYFRAMEINTERVAL), UDM_SETRANGE32, 0, 20); SendMessage(GetDlgItem(hwnd, IDC_KEYFRAMEINTERVAL), UDM_SETPOS32, 0, keyframeInt); //-------------------------------------------- bool bUnlockFPS = AppConfig->GetInt(TEXT("Video"), TEXT("UnlockFPS")) != 0; SendMessage(GetDlgItem(hwnd, IDC_UNLOCKHIGHFPS), BM_SETCHECK, bUnlockFPS ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ bHasQSV = CheckQSVHardwareSupport(false); bool bUseQSV = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseQSV")) != 0; bHasNVENC = CheckNVENCHardwareSupport(false); bool bUseNVENC = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseNVENC")) != 0; EnableWindow(GetDlgItem(hwnd, IDC_USEQSV), (bHasQSV || bUseQSV) && !bUseNVENC); SendMessage(GetDlgItem(hwnd, IDC_USEQSV), BM_SETCHECK, bUseQSV ? BST_CHECKED : BST_UNCHECKED, 0); bool bQSVUseVideoEncoderSettings = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("QSVUseVideoEncoderSettings")) != 0; SendMessage(GetDlgItem(hwnd, IDC_QSVUSEVIDEOENCODERSETTINGS), BM_SETCHECK, bQSVUseVideoEncoderSettings ? BST_CHECKED : BST_UNCHECKED, 0); ti.lpszText = (LPWSTR)Str("Settings.Advanced.QSVUseVideoEncoderSettingsTooltip"); ti.uId = (UINT_PTR)GetDlgItem(hwnd, IDC_QSVUSEVIDEOENCODERSETTINGS); SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); EnableWindow(GetDlgItem(hwnd, IDC_QSVUSEVIDEOENCODERSETTINGS), bUseQSV && !bUseNVENC); EnableWindow(GetDlgItem(hwnd, IDC_USENVENC), (bHasNVENC || bUseNVENC) && !bUseQSV); SendMessage(GetDlgItem(hwnd, IDC_USENVENC), BM_SETCHECK, bUseNVENC ? BST_CHECKED : BST_UNCHECKED, 0); hwndTemp = GetDlgItem(hwnd, IDC_NVENCPRESET); EnableWindow(hwndTemp, bHasNVENC && bUseNVENC && !bUseQSV); static const CTSTR nv_preset_names[8] = { TEXT("High Quality"), TEXT("High Performance"), TEXT("Bluray Disk"), TEXT("Low Latency"), TEXT("High Performance Low Latency"), TEXT("High Quality Low Latency"), TEXT("Default"), NULL }; for (int i = 0; nv_preset_names[i]; i++) SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)nv_preset_names[i]); LoadSettingComboString(hwndTemp, TEXT("Video Encoding"), TEXT("NVENCPreset"), nv_preset_names[0]); //------------------------------------ bool bSyncToVideoTime = AppConfig->GetInt(TEXT("Audio"), TEXT("SyncToVideoTime")) != 0; SendMessage(GetDlgItem(hwnd, IDC_SYNCTOVIDEOTIME), BM_SETCHECK, bSyncToVideoTime ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ bool bUseMicQPC = GlobalConfig->GetInt(TEXT("Audio"), TEXT("UseMicQPC")) != 0; SendMessage(GetDlgItem(hwnd, IDC_USEMICQPC), BM_SETCHECK, bUseMicQPC ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ BOOL bMicSyncFixHack = GlobalConfig->GetInt(TEXT("Audio"), TEXT("UseMicSyncFixHack")); SendMessage(GetDlgItem(hwnd, IDC_MICSYNCFIX), BM_SETCHECK, bMicSyncFixHack ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ int bufferTime = GlobalConfig->GetInt(TEXT("General"), TEXT("SceneBufferingTime"), 700); int globalAudioTimeAdjust = GlobalConfig->GetInt(TEXT("Audio"), TEXT("GlobalAudioTimeAdjust")); SendMessage(GetDlgItem(hwnd, IDC_AUDIOTIMEADJUST), UDM_SETRANGE32, -bufferTime, 5000); SendMessage(GetDlgItem(hwnd, IDC_AUDIOTIMEADJUST), UDM_SETPOS32, 0, globalAudioTimeAdjust); //------------------------------------ int lowLatencyFactor = AppConfig->GetInt(TEXT("Publish"), TEXT("LatencyFactor"), 20); SetDlgItemInt(hwnd, IDC_LATENCYTUNE, lowLatencyFactor, TRUE); int bLowLatencyAutoMethod = AppConfig->GetInt(TEXT("Publish"), TEXT("LowLatencyMethod"), 0); SendMessage(GetDlgItem(hwnd, IDC_LATENCYMETHOD), BM_SETCHECK, bLowLatencyAutoMethod ? BST_CHECKED : BST_UNCHECKED, 0); //------------------------------------ MIB_IPADDRTABLE tempTable; DWORD dwSize = 0; if (GetIpAddrTable (&tempTable, &dwSize, TRUE) == ERROR_INSUFFICIENT_BUFFER) { PMIB_IPADDRTABLE ipTable; ipTable = (PMIB_IPADDRTABLE)Allocate(dwSize); if (GetIpAddrTable (ipTable, &dwSize, TRUE) == NO_ERROR) { DWORD i; hwndTemp = GetDlgItem(hwnd, IDC_BINDIP); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("Default")); for (i=0; i < ipTable->dwNumEntries; i++) { String strAddress; DWORD strLength = 32; // don't allow binding to localhost if ((ipTable->table[i].dwAddr & 0xFF) == 127) continue; strAddress.SetLength(strLength); SOCKADDR_IN IP; IP.sin_addr.S_un.S_addr = ipTable->table[i].dwAddr; IP.sin_family = AF_INET; IP.sin_port = 0; zero(&IP.sin_zero, sizeof(IP.sin_zero)); WSAAddressToString ((LPSOCKADDR)&IP, sizeof(IP), NULL, strAddress.Array(), &strLength); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)strAddress.Array()); } LoadSettingComboString(hwndTemp, TEXT("Publish"), TEXT("BindToIP"), TEXT("Default")); } Free(ipTable); } //need this as some of the dialog item sets above trigger the notifications ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_HIDE); SetChangedSettings(false); return TRUE; } case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_USEVIDEOENCODERSETTINGS: if(HIWORD(wParam) == BN_CLICKED) { BOOL bUseVideoEncoderSettings = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED; EnableWindow(GetDlgItem(hwnd, IDC_VIDEOENCODERSETTINGS), bUseVideoEncoderSettings); ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; case IDC_KEYFRAMEINTERVAL_EDIT: case IDC_SCENEBUFFERTIME_EDIT: case IDC_AUDIOTIMEADJUST_EDIT: case IDC_VIDEOENCODERSETTINGS: case IDC_LATENCYTUNE: if(HIWORD(wParam) == EN_CHANGE) { ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; /*case IDC_TIMER1: case IDC_TIMER2: case IDC_TIMER3: case IDC_DISABLED3DCOMPATIBILITY: if(HIWORD(wParam) == BN_CLICKED) { ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break;*/ case IDC_USESENDBUFFER: if(HIWORD(wParam) == BN_CLICKED) { BOOL bUseSendBuffer = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED; EnableWindow(GetDlgItem(hwnd, IDC_SENDBUFFERSIZE), bUseSendBuffer); ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; case IDC_PRESET: if(HIWORD(wParam) == CBN_SELCHANGE) { HWND hwndTemp = (HWND)lParam; String strNewPreset = GetCBText(hwndTemp); if (scmp(strNewPreset.Array(), TEXT("veryfast"))) { static BOOL bHasWarned = FALSE; if (!bHasWarned && MessageBox(hwnd, Str("Settings.Advanced.PresetWarning"), NULL, MB_ICONEXCLAMATION | MB_YESNO) == IDNO) LoadSettingComboString(hwndTemp, TEXT("Video Encoding"), TEXT("Preset"), TEXT("veryfast")); else bHasWarned = TRUE; } SetChangedSettings(true); ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); } break; case IDC_X264PROFILE: case IDC_SENDBUFFERSIZE: case IDC_PRIORITY: case IDC_BINDIP: case IDC_NVENCPRESET: if(HIWORD(wParam) == CBN_SELCHANGE || HIWORD(wParam) == CBN_EDITCHANGE) { ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; case IDC_USEQSV: case IDC_USENVENC: if (HIWORD(wParam) == BN_CLICKED) { bool bUseQSV = SendMessage(GetDlgItem(hwnd, IDC_USEQSV), BM_GETCHECK, 0, 0) == BST_CHECKED; bool bUseNVENC = SendMessage(GetDlgItem(hwnd, IDC_USENVENC), BM_GETCHECK, 0, 0) == BST_CHECKED; bool bUseQSV_prev = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseQSV")) != 0; bool bUseNVENC_prev = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseNVENC")) != 0; EnableWindow(GetDlgItem(hwnd, IDC_QSVUSEVIDEOENCODERSETTINGS), (bHasQSV || bUseQSV) && !bUseNVENC); EnableWindow(GetDlgItem(hwnd, IDC_USEQSV), !bUseNVENC && (bHasQSV || bUseQSV_prev)); EnableWindow(GetDlgItem(hwnd, IDC_USENVENC), !bUseQSV && (bHasNVENC || bUseNVENC_prev)); EnableWindow(GetDlgItem(hwnd, IDC_NVENCPRESET), !bUseQSV && bUseNVENC); } case IDC_DISABLEPREVIEWENCODING: case IDC_ALLOWOTHERHOTKEYMODIFIERS: case IDC_MICSYNCFIX: case IDC_USEMICQPC: case IDC_SYNCTOVIDEOTIME: case IDC_USECFR: case IDC_USEMULTITHREADEDOPTIMIZATIONS: case IDC_UNLOCKHIGHFPS: case IDC_LATENCYMETHOD: case IDC_QSVUSEVIDEOENCODERSETTINGS: if(HIWORD(wParam) == BN_CLICKED) { ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; } } return FALSE; }
vector<float> CircularBuffer::creatHistogram(int partitionN){ vector<float> histogram(8 * partitionN); float angle; float mod; int frameN = maxSize/partitionN; for(int j = 0; j < partitionN; ++j){ for(int i = j * frameN; i < (j + 1) * frameN; ++i){ int pos = startPoint + i; if(pos >= maxSize) pos = pos - maxSize; if(!zero(v[pos])){ mod = getMod(v[pos]); if(v[pos].first == 0 && v[pos].second > 0){//positive y direction histogram[2 + 8 * j] += mod; continue; }else if(v[pos].first == 0 && v[pos].second < 0){//negative y direction histogram[6 + 8 * j] += mod; continue; }else if(v[pos].second == 0 && v[pos].first > 0){//positive x direction histogram[0 + 8 * j] += mod; continue; }else{//negative x direction histogram[4 + 8 * j] += mod; continue; } angle = atan((v[pos].second*1.0)/v[pos].first); if(v[pos].first > 0 && v[pos].second > 0){//positive x and positive y region if(angle <= 3.1415926/4){ histogram[0 + 8 * j] += mod; continue; } if(angle > 3.1415926/4 && angle < 3.1415926/2){ histogram[1 + 8 * j] += mod; continue; } }else if(v[pos].first > 0 && v[pos].second < 0){//positive x and negative y region if(angle > 3.1415926/4){ histogram[7 + 8 * j] += mod; continue; } if(angle > -3.1415926/2 && angle < -3.1415926/4){ histogram[6 + 8 * j] += mod; continue; } }else if(v[pos].first < 0 && v[pos].second > 0){//negative x and positive y region if(angle > -3.1415926/4){ histogram[3 + 8 * j] += mod; continue; } if(angle > -3.1415926/2 && angle < -3.1415926/4){ histogram[2 + 8 * j] += mod; continue; } }else if(v[pos].first < 0 && v[pos].second < 0){//negative x and negative y region if(angle <= 3.1415926/4){ histogram[4 + 8 * j] += mod; continue; } if(angle > 3.1415926/4 && angle < 3.1415926/2){ histogram[5 + 8 * j] += mod; continue; } } }//end of if }//end of for } for(int i = 0; i < 8 * partitionN; ++i){ histogram[i] /= frameN * 1.0; } return histogram; }
void GraphicsCaptureSource::AttemptCapture() { if (!bUseHotkey) hwndTarget = FindWindow(strWindowClass, NULL); else { hwndTarget = hwndNextTarget; hwndNextTarget = NULL; } if (hwndTarget) { GetWindowThreadProcessId(hwndTarget, &targetProcessID); if(!targetProcessID) { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: GetWindowThreadProcessId failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; return; } } else { if (!bUseHotkey && !warningID) warningID = API->AddStreamInfo(Str("Sources.SoftwareCaptureSource.WindowNotFound"), StreamInfoPriority_High); bCapturing = false; return; } if(warningID) { API->RemoveStreamInfo(warningID); warningID = 0; } //------------------------------------------- // see if we already hooked the process. if not, inject DLL char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); //OpenProcess obfuscated for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); HANDLE hProcess = (*pOpenProcess)(PROCESS_ALL_ACCESS, FALSE, targetProcessID); if(hProcess) { //------------------------------------------- // load keepalive event hOBSIsAlive = CreateEvent(NULL, FALSE, FALSE, String() << OBS_KEEPALIVE_EVENT << int(targetProcessID)); //------------------------------------------- hwndCapture = hwndTarget; hSignalRestart = OpenEvent(EVENT_ALL_ACCESS, FALSE, String() << RESTART_CAPTURE_EVENT << int(targetProcessID)); if(hSignalRestart) { SetEvent(hSignalRestart); bCapturing = true; captureWaitCount = 0; } else { BOOL bSameBit = TRUE; if(Is64BitWindows()) { BOOL bCurrentProcessWow64, bTargetProcessWow64; IsWow64Process(GetCurrentProcess(), &bCurrentProcessWow64); IsWow64Process(hProcess, &bTargetProcessWow64); bSameBit = (bCurrentProcessWow64 == bTargetProcessWow64); } if(bSameBit) { String strDLL; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLL.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLL); strDLL << TEXT("\\plugins\\GraphicsCapture\\GraphicsCaptureHook"); BOOL b32bit = TRUE; if(Is64BitWindows()) IsWow64Process(hProcess, &b32bit); if(!b32bit) strDLL << TEXT("64"); strDLL << TEXT(".dll"); if(InjectLibrary(hProcess, strDLL)) { captureWaitCount = 0; bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: Failed to inject library, GetLastError = %u"), GetLastError()); CloseHandle(hProcess); hProcess = NULL; bErrorAcquiring = true; } } else { String strDLLPath; DWORD dwDirSize = GetCurrentDirectory(0, NULL); strDLLPath.SetLength(dwDirSize); GetCurrentDirectory(dwDirSize, strDLLPath); strDLLPath << TEXT("\\plugins\\GraphicsCapture"); BOOL b32bit = TRUE; if(Is64BitWindows()) IsWow64Process(hProcess, &b32bit); String strHelper = strDLLPath; strHelper << ((b32bit) ? TEXT("\\injectHelper.exe") : TEXT("\\injectHelper64.exe")); String strCommandLine; strCommandLine << TEXT("\"") << strHelper << TEXT("\" ") << UIntString(targetProcessID); //--------------------------------------- PROCESS_INFORMATION pi; STARTUPINFO si; zero(&pi, sizeof(pi)); zero(&si, sizeof(si)); si.cb = sizeof(si); if(CreateProcess(strHelper, strCommandLine, NULL, NULL, FALSE, 0, NULL, strDLLPath, &si, &pi)) { int exitCode = 0; WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, (DWORD*)&exitCode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); if(exitCode == 0) { captureWaitCount = 0; bCapturing = true; } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: Failed to inject library, error code = %d"), exitCode); bErrorAcquiring = true; } } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: Could not create inject helper, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } } } CloseHandle(hProcess); hProcess = NULL; if (!bCapturing) { CloseHandle(hOBSIsAlive); hOBSIsAlive = NULL; } } else { AppWarning(TEXT("GraphicsCaptureSource::BeginScene: OpenProcess failed, GetLastError = %u"), GetLastError()); bErrorAcquiring = true; } }
LRESULT CALLBACK VolumeControlProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { VolumeControlData *control; switch(message) { case WM_NCCREATE: { CREATESTRUCT *pCreateData = (CREATESTRUCT*)lParam; control = (VolumeControlData*)malloc(sizeof(VolumeControlData)); zero(control, sizeof(VolumeControlData)); SetWindowLongPtr(hwnd, 0, (LONG_PTR)control); control->curVolume = 1.0f; control->bDisabled = ((pCreateData->style & WS_DISABLED) != 0); control->cx = pCreateData->cx; control->cy = pCreateData->cy; return TRUE; } case WM_DESTROY: { control = GetVolumeControlData(hwnd); if(control) free(control); break; } case WM_PAINT: { control = GetVolumeControlData(hwnd); PAINTSTRUCT ps; HDC hDC = BeginPaint(hwnd, &ps); control->DrawVolumeControl(hDC); EndPaint(hwnd, &ps); break; } case WM_LBUTTONDOWN: case WM_LBUTTONUP: { control = GetVolumeControlData(hwnd); short x = short(LOWORD(lParam)); short y = short(HIWORD(lParam)); UINT id = (UINT)GetWindowLongPtr(hwnd, GWLP_ID); if(message == WM_LBUTTONDOWN && !control->bDisabled) { if(control->cy == 32 && x >= (control->cx-32)) { if(control->curVolume < 0.05f) { if(control->lastUnmutedVol < 0.05f) control->lastUnmutedVol = 1.0f; control->curVolume = control->lastUnmutedVol; } else { control->lastUnmutedVol = control->curVolume; control->curVolume = 0.0f; } SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(id, VOLN_FINALVALUE), (LPARAM)hwnd); } else { SetCapture(hwnd); control->bHasCapture = true; if(control->curVolume > 0.05f) control->lastUnmutedVol = control->curVolume; int cxAdjust = control->cx; if(control->bDrawIcon) cxAdjust -= 32; control->curVolume = float(x) / cxAdjust; SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(id, VOLN_ADJUSTING), (LPARAM)hwnd); } HDC hDC = GetDC(hwnd); control->DrawVolumeControl(hDC); ReleaseDC(hwnd, hDC); } else if(control->bHasCapture) { UINT id = (UINT)GetWindowLongPtr(hwnd, GWLP_ID); SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(id, VOLN_FINALVALUE), (LPARAM)hwnd); ReleaseCapture(); control->bHasCapture = false; } break; } case WM_MOUSEMOVE: { control = GetVolumeControlData(hwnd); if(control->bHasCapture) { int cxAdjust = control->cx; if(control->bDrawIcon) cxAdjust -= 32; control->curVolume = float(short(LOWORD(lParam))) / cxAdjust; if(control->curVolume < 0.0f) control->curVolume = 0.0f; else if(control->curVolume > 1.0f) control->curVolume = 1.0f; HDC hDC = GetDC(hwnd); control->DrawVolumeControl(hDC); ReleaseDC(hwnd, hDC); UINT id = (UINT)GetWindowLongPtr(hwnd, GWLP_ID); SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(id, VOLN_ADJUSTING), (LPARAM)hwnd); } break; } case WM_ENABLE: { UINT id = (UINT)GetWindowLongPtr(hwnd, GWLP_ID); control = GetVolumeControlData(hwnd); if(control->bDisabled == !wParam) break; control->bDisabled = !control->bDisabled; if(control->bDisabled) { if(control->curVolume > 0.05f) { control->lastUnmutedVol = control->curVolume; control->curVolume = 0.0f; SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(id, VOLN_ADJUSTING), (LPARAM)hwnd); } } else { if(control->curVolume < 0.05f) { control->curVolume = control->lastUnmutedVol; SendMessage(GetParent(hwnd), WM_COMMAND, MAKEWPARAM(id, VOLN_ADJUSTING), (LPARAM)hwnd); } } HDC hDC = GetDC(hwnd); control->DrawVolumeControl(hDC); ReleaseDC(hwnd, hDC); break; } case WM_SIZE: { control = GetVolumeControlData(hwnd); control->cx = LOWORD(lParam); control->cy = HIWORD(lParam); control->bDrawIcon = (control->cy == 32) && control->hiconPlay; HDC hDC = GetDC(hwnd); control->DrawVolumeControl(hDC); ReleaseDC(hwnd, hDC); break; } default: return DefWindowProc(hwnd, message, wParam, lParam); } return 0; }
int egcd(_MIPD_ big x,big y,big z) { /* greatest common divisor z=gcd(x,y) by Euclids * * method using Lehmers algorithm for big numbers */ int q,r,a,b,c,d,n; mr_small sr,m,sm; mr_small u,v,lq,lr; #ifdef MR_FP mr_small dres; #endif big t; #ifdef MR_OS_THREADS miracl *mr_mip=get_mip(); #endif if (mr_mip->ERNUM) return 0; MR_IN(12) copy(x,mr_mip->w1); copy(y,mr_mip->w2); insign(PLUS,mr_mip->w1); insign(PLUS,mr_mip->w2); a=b=c=d=0; while (size(mr_mip->w2)!=0) { /* printf("a= %d b= %d c= %d d=%d\n",a,b,c,d); */ if (b==0) { /* update w1 and w2 */ divide(_MIPP_ mr_mip->w1,mr_mip->w2,mr_mip->w2); t=mr_mip->w1,mr_mip->w1=mr_mip->w2,mr_mip->w2=t; /* swap(w1,w2) */ } else { premult(_MIPP_ mr_mip->w1,c,z); premult(_MIPP_ mr_mip->w1,a,mr_mip->w1); premult(_MIPP_ mr_mip->w2,b,mr_mip->w0); premult(_MIPP_ mr_mip->w2,d,mr_mip->w2); add(_MIPP_ mr_mip->w1,mr_mip->w0,mr_mip->w1); add(_MIPP_ mr_mip->w2,z,mr_mip->w2); } if (mr_mip->ERNUM || size(mr_mip->w2)==0) break; n=(int)mr_mip->w1->len; if (mr_mip->w2->len==1) { /* special case if mr_mip->w2 is now small */ sm=mr_mip->w2->w[0]; #ifdef MR_FP_ROUNDING sr=mr_sdiv(_MIPP_ mr_mip->w1,sm,mr_invert(sm),mr_mip->w1); #else sr=mr_sdiv(_MIPP_ mr_mip->w1,sm,mr_mip->w1); #endif if (sr==0) { copy(mr_mip->w2,mr_mip->w1); break; } zero(mr_mip->w1); mr_mip->w1->len=1; mr_mip->w1->w[0]=sr; while ((sr=MR_REMAIN(mr_mip->w2->w[0],mr_mip->w1->w[0]))!=0) mr_mip->w2->w[0]=mr_mip->w1->w[0],mr_mip->w1->w[0]=sr; break; } a=1; b=0; c=0; d=1; m=mr_mip->w1->w[n-1]+1; /* printf("m= %d\n",m); */ #ifndef MR_SIMPLE_BASE if (mr_mip->base==0) { #endif #ifndef MR_NOFULLWIDTH if (m==0) { u=mr_mip->w1->w[n-1]; v=mr_mip->w2->w[n-1]; } else { /* printf("w1[n-1]= %d w1[n-2]= %d\n", mr_mip->w1->w[n-1],mr_mip->w1->w[n-2]); printf("w2[n-1]= %d w2[n-2]= %d\n", mr_mip->w2->w[n-1],mr_mip->w2->w[n-2]);*/ u=muldvm(mr_mip->w1->w[n-1],mr_mip->w1->w[n-2],m,&sr); v=muldvm(mr_mip->w2->w[n-1],mr_mip->w2->w[n-2],m,&sr); } #endif #ifndef MR_SIMPLE_BASE } else { u=muldiv(mr_mip->w1->w[n-1],mr_mip->base,mr_mip->w1->w[n-2],m,&sr); v=muldiv(mr_mip->w2->w[n-1],mr_mip->base,mr_mip->w2->w[n-2],m,&sr); } #endif /* printf("u= %d v= %d\n",u,v);*/ forever { /* work only with most significant piece */ if (((v+c)==0) || ((v+d)==0)) break; lq=MR_DIV((u+a),(v+c)); if (lq!=MR_DIV((u+b),(v+d))) break; if (lq>=(mr_small)(MR_TOOBIG/mr_abs(d))) break; q=(int)lq; r=a-q*c; a=c; c=r; r=b-q*d; b=d; d=r; lr=u-lq*v; u=v; v=lr; } } copy(mr_mip->w1,z); MR_OUT return (size(mr_mip->w1)); }
INT_PTR SettingsEncoding::ProcMessage(UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_INITDIALOG: { HWND hwndTemp; LocalizeWindow(hwnd); //-------------------------------------------- HWND hwndToolTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL, WS_POPUP|TTS_NOPREFIX|TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwnd, NULL, hinstMain, NULL); TOOLINFO ti; zero(&ti, sizeof(ti)); ti.cbSize = sizeof(ti); ti.uFlags = TTF_SUBCLASS|TTF_IDISHWND; ti.hwnd = hwnd; SendMessage(hwndToolTip, TTM_SETMAXTIPWIDTH, 0, 500); SendMessage(hwndToolTip, TTM_SETDELAYTIME, TTDT_AUTOPOP, 8000); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_QUALITY); for(int i=0; i<=10; i++) SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)IntString(i).Array()); LoadSettingComboString(hwndTemp, TEXT("Video Encoding"), TEXT("Quality"), TEXT("8")); ti.lpszText = (LPWSTR)Str("Settings.Encoding.Video.QualityTooltip"); ti.uId = (UINT_PTR)hwndTemp; SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); //-------------------------------------------- bool bUseCBR = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseCBR"), 1) != 0; SendMessage(GetDlgItem(hwnd, IDC_USECBR), BM_SETCHECK, bUseCBR ? BST_CHECKED : BST_UNCHECKED, 0); EnableWindow(GetDlgItem(hwnd, IDC_QUALITY), !bUseCBR); //-------------------------------------------- int bitrate = LoadSettingEditInt(GetDlgItem(hwnd, IDC_MAXBITRATE), TEXT("Video Encoding"), TEXT("MaxBitrate"), 1000); int buffersize = LoadSettingEditInt(GetDlgItem(hwnd, IDC_BUFFERSIZE), TEXT("Video Encoding"), TEXT("BufferSize"), 1000); ti.lpszText = (LPWSTR)Str("Settings.Encoding.Video.MaxBitRateTooltip"); ti.uId = (UINT_PTR)GetDlgItem(hwnd, IDC_MAXBITRATE); SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); ti.lpszText = (LPWSTR)Str("Settings.Encoding.Video.BufferSizeTooltip"); ti.uId = (UINT_PTR)GetDlgItem(hwnd, IDC_BUFFERSIZE); SendMessage(hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); //-------------------------------------------- bool bHasUseBufferSizeValue = AppConfig->HasKey(TEXT("Video Encoding"), TEXT("UseBufferSize")) != 0; bool bUseBufferSize; if(!bHasUseBufferSizeValue) bUseBufferSize = buffersize != bitrate; else bUseBufferSize = AppConfig->GetInt(TEXT("Video Encoding"), TEXT("UseBufferSize"), 0) != 0; SendMessage(GetDlgItem(hwnd, IDC_CUSTOMBUFFER), BM_SETCHECK, bUseBufferSize ? BST_CHECKED : BST_UNCHECKED, 0); EnableWindow(GetDlgItem(hwnd, IDC_BUFFERSIZE), bUseBufferSize); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_AUDIOCODEC); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("MP3")); #ifdef USE_AAC if(OSGetVersion() >= 7) { SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("AAC")); LoadSettingComboString(hwndTemp, TEXT("Audio Encoding"), TEXT("Codec"), TEXT("AAC")); } else LoadSettingComboString(hwndTemp, TEXT("Audio Encoding"), TEXT("Codec"), TEXT("MP3")); #else LoadSettingComboString(hwndTemp, TEXT("Audio Encoding"), TEXT("Codec"), TEXT("MP3")); #endif //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_AUDIOBITRATE); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("48")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("64")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("80")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("96")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("112")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("128")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("160")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("192")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("256")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("320")); LoadSettingComboString(hwndTemp, TEXT("Audio Encoding"), TEXT("Bitrate"), TEXT("96")); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_AUDIOFORMAT); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("44.1khz mono")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("44.1khz stereo")); LoadSettingComboInt(hwndTemp, TEXT("Audio Encoding"), TEXT("Format"), 1, 1); //-------------------------------------------- ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_HIDE); SetChangedSettings(false); return TRUE; } case WM_COMMAND: { bool bDataChanged = false; switch(LOWORD(wParam)) { case IDC_QUALITY: case IDC_AUDIOCODEC: case IDC_AUDIOBITRATE: case IDC_AUDIOFORMAT: if(HIWORD(wParam) == CBN_SELCHANGE) bDataChanged = true; break; case IDC_MAXBITRATE: if(HIWORD(wParam) == EN_CHANGE) { bool bCustomBuffer = SendMessage(GetDlgItem(hwnd, IDC_CUSTOMBUFFER), BM_GETCHECK, 0, 0) == BST_CHECKED; if (!bCustomBuffer) { String strText = GetEditText((HWND)lParam); SetWindowText(GetDlgItem(hwnd, IDC_BUFFERSIZE), strText); } bDataChanged = true; } break; case IDC_BUFFERSIZE: if(HIWORD(wParam) == EN_CHANGE) bDataChanged = true; break; case IDC_CUSTOMBUFFER: case IDC_USECBR: if (HIWORD(wParam) == BN_CLICKED) { bool bChecked = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED; if(LOWORD(wParam) == IDC_CUSTOMBUFFER) { EnableWindow(GetDlgItem(hwnd, IDC_BUFFERSIZE), bChecked); if(!bChecked) SetWindowText(GetDlgItem(hwnd, IDC_BUFFERSIZE), GetEditText(GetDlgItem(hwnd, IDC_MAXBITRATE))); } else if(LOWORD(wParam) == IDC_USECBR) EnableWindow(GetDlgItem(hwnd, IDC_QUALITY), !bChecked); bDataChanged = true; } break; } if(bDataChanged) { ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; } } return FALSE; }
void Density::generate_valence(K_set& ks__) { PROFILE_WITH_TIMER("sirius::Density::generate_valence"); double wt = 0.0; double ot = 0.0; for (int ik = 0; ik < ks__.num_kpoints(); ik++) { wt += ks__[ik]->weight(); for (int j = 0; j < ctx_.num_bands(); j++) ot += ks__[ik]->weight() * ks__[ik]->band_occupancy(j); } if (std::abs(wt - 1.0) > 1e-12) TERMINATE("K_point weights don't sum to one"); if (std::abs(ot - unit_cell_.num_valence_electrons()) > 1e-8) { std::stringstream s; s << "wrong occupancies" << std::endl << " computed : " << ot << std::endl << " required : " << unit_cell_.num_valence_electrons() << std::endl << " difference : " << std::abs(ot - unit_cell_.num_valence_electrons()); WARNING(s); } /* swap wave functions */ for (int ikloc = 0; ikloc < ks__.spl_num_kpoints().local_size(); ikloc++) { int ik = ks__.spl_num_kpoints(ikloc); auto kp = ks__[ik]; for (int ispn = 0; ispn < ctx_.num_spins(); ispn++) { if (ctx_.full_potential()) { kp->spinor_wave_functions<true>(ispn).swap_forward(0, kp->num_occupied_bands(ispn)); } else { kp->spinor_wave_functions<false>(ispn).swap_forward(0, kp->num_occupied_bands(ispn), kp->gkvec_fft_distr()); } } } /* zero density and magnetization */ zero(); ctx_.fft().prepare(); /* interstitial part is independent of basis type */ generate_valence_density_it(ks__); /* for muffin-tin part */ switch (ctx_.esm_type()) { case full_potential_lapwlo: { generate_valence_density_mt(ks__); break; } case full_potential_pwlo: { STOP(); } default: { break; } } #if (__VERIFICATION > 0) for (int ir = 0; ir < ctx_.fft(0)->local_size(); ir++) { if (rho_->f_it(ir) < 0) TERMINATE("density is wrong"); } #endif //== double nel = 0; //== for (int ir = 0; ir < ctx_.fft().local_size(); ir++) //== { //== nel += rho_->f_rg(ir); //== } //== ctx_.mpi_grid().communicator(1 << _dim_row_).allreduce(&nel, 1); //== nel = nel * unit_cell_.omega() / ctx_.fft().size(); //== printf("number of electrons: %f\n", nel); /* get rho(G) and mag(G) */ rho_->fft_transform(-1); for (int j = 0; j < ctx_.num_mag_dims(); j++) magnetization_[j]->fft_transform(-1); //== printf("number of electrons: %f\n", rho_->f_pw(0).real() * unit_cell_.omega()); //== STOP(); ctx_.fft().dismiss(); if (ctx_.esm_type() == ultrasoft_pseudopotential) augment(ks__); }
int main(int argc, char *argv[]) { long n; float *A; float *B; float *C_seq; float *C_ompacc; double seq_elapsed; double ompacc_elapsed; if (argc < 2) { fprintf(stderr, "Usage: matmul <n> [dist_dim(1|2|3)] [dist_policy(1|2|3)]\\n"); fprintf(stderr, "\tn: matrix size (nxn)\n"); fprintf(stderr, "\tdist_dim: 1: row dist; 2: column dist; 3: both row/column dist; default 1\n"); fprintf(stderr, "\tdist_policy: 1: block_block; 2: block_align; 3: auto_align; default 1\n"); exit(1); } n = atoi(argv[1]); int dist_dim = 1; int dist_policy = 1; if (argc == 3) dist_dim = atoi(argv[2]); if (argc == 4) dist_policy = atoi(argv[3]); if (dist_dim != 1 && dist_dim != 2 && dist_dim != 3) { fprintf(stderr, "Unknown dist dimensions: %d, now fall to default (1)\n", dist_dim); dist_dim = 1; } if (dist_policy != 1 && dist_policy != 2 && dist_policy != 3) { fprintf(stderr, "Unknown dist policy: %d, now fall to default (1)\n", dist_policy); dist_policy = 1; } A = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); B = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); C_seq = ((float *) (malloc(((n * n) * sizeof(float))))); C_ompacc = ((float *) (omp_unified_malloc(((n * n) * sizeof(float))))); srand48((1 << 12)); init(A, n); init(B, n); // print_array("Array A", "A", A, n, n); // print_array("Array B", "B", B, n, n); zero(C_seq, n); zero(C_ompacc, n); /* sequential run */ seq_elapsed = read_timer_ms(); int i; int num_its = 10; for (i=0; i<num_its;i++) iter_matmul(A, B, C_seq, n); seq_elapsed = (read_timer_ms() - seq_elapsed)/num_its; // print_array("Array C_seq", "C", C_seq, n, n); /* we currently cannot do the OpenMP acc and OpenACC run in once */ /* openmp acc version */ omp_init_devices(); ompacc_elapsed = matmul_ompacc_mdev(A, B, C_ompacc, n, dist_dim, dist_policy); //print_array("Array C_ompacc", "C", C_ompacc, n, n); omp_fini_devices(); printf("======================================================================================================\n"); printf("\tmatmul(%dx%d) example on %d devices, dist policy: %d (1: row; 2: column; 3: row-column)\n", n, n, omp_get_num_active_devices(), dist_dim); printf("------------------------------------------------------------------------------------------------------\n"); printf("Error: %g\n", maxerror(C_seq, C_ompacc, n)); printf("------------------------------------------------------------------------------------------------------\n"); printf("Performance:\t\tRuntime (ms)\t MFLOPS\n"); printf("Sequential:\t\t%4f\t%4f\n", seq_elapsed, ((((2.0 * n) * n) * n) / (1.0e3 * seq_elapsed))); printf("OMPACC mdev:\t\t%4f\t%4f\n", ompacc_elapsed, ((((2.0 * n) * n) * n) / (1.0e3 * ompacc_elapsed))); omp_unified_free(C_ompacc); free(C_seq); omp_unified_free(B); omp_unified_free(A); return 0; }
//Perform the operation given by the CPU void ALU::operation(int code, Register a, Register b) { //Reset all flags that aren't required m_flags[1] = 0; m_flags[2] = 0; m_flags[3] = 0; //Check if unary operation if(!(code==0||code==1||code==4||code==9||code==13||code==16||code==17||code==18||code==19||code==20)) { //Compare a and b if possible and set flags if(a.getValue()>b.getValue()) { m_flags[1] = 1; } else if(a.getValue()==b.getValue()) { m_flags[2] = 1; } } //Perform operation based on code (sets carry flag to 0 if it isn't set in the operation) if(code==0) { zero(a); m_flags[0] = 0; } else if(code==1) { one(a); m_flags[0] = 0; } else if(code==2) { add(a,b); } else if(code==3) { addc(a,b); } else if(code==4) { inc(a); } else if(code==5) { sub(a,b); } else if(code==6) { subc(a,b); } else if(code==7) { rsub(a,b); } else if(code==8) { rsubc(a,b); } else if(code==9) { dec(a); } else if(code==10) { mul(a,b); } else if(code==11) { random(a); m_flags[0] = 0; } else if(code==16) { shl(a); } else if(code==17) { shlc(a); } else if(code==18) { shr(a); } else if(code==19) { shrc(a); } else if(code==20) { not(a); m_flags[0] = 0; } else if(code==21) { and(a,b); m_flags[0] = 0; } else if(code==22) { nand(a,b); m_flags[0] = 0; } else if(code==23) { or(a,b); m_flags[0] = 0; } else if(code==24) { nor(a,b); m_flags[0] = 0; } else if(code==25) { xor(a,b); m_flags[0] = 0; } else if(code==26) { xnor(a,b); m_flags[0] = 0; } else if(code==27) { bclr(a,b); m_flags[0] = 0; } else if(code==31) { m_flags[0] = 0; } //Check if output is 0 and set flag accordingly if(a.getValue()) { m_flags[3]=1; } }
struct raw_iface *find_raw_ifaces4(void) { static const int on = TRUE; /* by-reference parameter; constant, we hope */ int j; /* index into buf */ struct ifconf ifconf; struct ifreq *buf = NULL; /* for list of interfaces -- arbitrary limit */ struct raw_iface *rifaces = NULL; int master_sock = safe_socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); /* Get a UDP socket */ /* * Current upper bound on number of interfaces. * Tricky: because this is a static, we won't have to start from * 64 in subsequent calls. */ static int num = 64; /* get list of interfaces with assigned IPv4 addresses from system */ if (master_sock == -1) exit_log_errno((e, "socket() failed in find_raw_ifaces4()")); if (setsockopt(master_sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0) exit_log_errno((e, "setsockopt() in find_raw_ifaces4()")); /* bind the socket */ { ip_address any; happy(anyaddr(AF_INET, &any)); setportof(htons(pluto_port), &any); if (bind(master_sock, sockaddrof(&any), sockaddrlenof(&any)) < 0) exit_log_errno((e, "bind() failed in find_raw_ifaces4()")); } /* a million interfaces is probably the maximum, ever... */ for (; num < (1024 * 1024); num *= 2) { /* Get num local interfaces. See netdevice(7). */ ifconf.ifc_len = num * sizeof(struct ifreq); buf = realloc(buf, ifconf.ifc_len); if (buf == NULL) { exit_log_errno((e, "realloc of %d in find_raw_ifaces4()", ifconf.ifc_len)); } memset(buf, 0xDF, ifconf.ifc_len); /* stomp */ ifconf.ifc_buf = (void *) buf; if (ioctl(master_sock, SIOCGIFCONF, &ifconf) == -1) exit_log_errno((e, "ioctl(SIOCGIFCONF) in find_raw_ifaces4()")); /* if we got back less than we asked for, we have them all */ if (ifconf.ifc_len < (int)(sizeof(struct ifreq) * num)) break; } /* Add an entry to rifaces for each interesting interface. */ for (j = 0; (j + 1) * sizeof(struct ifreq) <= (size_t)ifconf.ifc_len; j++) { struct raw_iface ri; const struct sockaddr_in *rs = (struct sockaddr_in *) &buf[j].ifr_addr; struct ifreq auxinfo; /* build a NUL-terminated copy of the rname field */ memcpy(ri.name, buf[j].ifr_name, IFNAMSIZ); ri.name[IFNAMSIZ] = '\0'; DBG(DBG_CONTROLMORE, DBG_log("Inspecting interface %s ", ri.name)); /* ignore all but AF_INET interfaces */ if (rs->sin_family != AF_INET) { DBG(DBG_CONTROLMORE, DBG_log("Ignoring non AF_INET interface %s ", ri.name)); continue; /* not interesting */ } /* ignore if our interface names were specified, and this isn't one - for KLIPS/MAST only */ if (pluto_ifn_roof != 0 && (kern_interface == USE_MASTKLIPS || kern_interface == USE_KLIPS)) { int i; DBG(DBG_CONTROLMORE, DBG_log("interfaces= specified, applying filter")); for (i = 0; i != pluto_ifn_roof; i++) if (streq(ri.name, pluto_ifn[i])) { DBG(DBG_CONTROLMORE, DBG_log("interface name '%s' found in interfaces= line", ri.name)); break; } if (i == pluto_ifn_roof) { DBG(DBG_CONTROLMORE, DBG_log("interface name '%s' not present in interfaces= line - skipped", ri.name)); continue; /* not found -- skip */ } } /* Find out stuff about this interface. See netdevice(7). */ zero(&auxinfo); /* paranoia */ memcpy(auxinfo.ifr_name, buf[j].ifr_name, IFNAMSIZ); if (ioctl(master_sock, SIOCGIFFLAGS, &auxinfo) == -1) { exit_log_errno((e, "ioctl(SIOCGIFFLAGS) for %s in find_raw_ifaces4()", ri.name)); } if (!(auxinfo.ifr_flags & IFF_UP)) { DBG(DBG_CONTROLMORE, DBG_log("Ignored interface %s - it is not up", ri.name)); continue; /* ignore an interface that isn't UP */ } if (auxinfo.ifr_flags & IFF_SLAVE) { DBG(DBG_CONTROLMORE, DBG_log("Ignored interface %s - it is a slave interface", ri.name)); continue; /* ignore slave interfaces; they share IPs with their master */ } /* ignore unconfigured interfaces */ if (rs->sin_addr.s_addr == 0) { DBG(DBG_CONTROLMORE, DBG_log("Ignored interface %s - it is unconfigured", ri.name)); continue; } happy(initaddr((const void *)&rs->sin_addr, sizeof(struct in_addr), AF_INET, &ri.addr)); DBG(DBG_CONTROLMORE, { ipstr_buf b; DBG_log("found %s with address %s", ri.name, ipstr(&ri.addr, &b)); }); ri.next = rifaces; rifaces = clone_thing(ri, "struct raw_iface"); }
void mp_real::mpadd(const mp_real &a, const mp_real &b, mp_real& c, int prec_words) { /** * This routine adds MP numbers A and B to yield the MP sum C. It attempts * to include all significance of A and B in the result, up to the maximum * mantissa length MPNW. Debug output starts with debug_level = 9. * This is a new simplified version. * * D contains the intermediate results of addition before normalization. * The first 3 words of D have special meanings: * d[0] : not accessed * d[1] : sign and number of words in D * d[2] : exponent * Before normalization, each word of D may have up to 53 bits and may be * negative. After normalization, each word is in [0, 2^mpnbt-1] */ double db; int i, ia, ib, ish, ixa, ixb, ixd, na, nb; int m1, m2, m3, m4, m5, nsh; double *d; int nd; // number of actual words in d[] if (error_no != 0) { zero(c); return; } if (debug_level >= 9) { print_mpreal("MPADD a ", a); print_mpreal("MPADD b ", b); } ia = a[1] >= 0 ? 1 : -1; ib = b[1] >= 0 ? 1 : -1; na = std::min (static_cast<int>(std::abs(a[1])), prec_words); // number of words in A nb = std::min (static_cast<int>(std::abs(b[1])), prec_words); // number of words in B /* Check for zero inputs. */ if (na == 0) { /* A is zero -- the result is B. */ int num_words = std::min(nb, int(c[0])-FST_M); c[1] = ib > 0 ? num_words : -num_words; for (i = 2; i < num_words + FST_M; ++i) c[i] = b[i]; return; } else if (nb == 0) { /* B is zero -- the result is A. */ int num_words = std::min(na, int(c[0])-FST_M); c[1] = ia >= 0 ? num_words : -num_words; for (i = 2; i < num_words + FST_M; ++i) c[i] = a[i]; return; } // get ready for main part of routine. d = new double[prec_words+7]; if (ia == ib) db = 1.0; //same signs - add else db = -1.0; // different signs - subtract ixa = static_cast<int>(a[2]); ixb = static_cast<int>(b[2]); ish = ixa - ixb; d[1] = 0.0; d[2] = 0.0; if (ish >= 0) { // |A| >= |B| // A has greater exponent than B, so B must be shifted to the right // to line up the radix point. m1 = std::min (na, ish); m2 = std::min (na, nb + ish); m3 = na; m4 = std::min (std::max (na, ish), prec_words + 1); m5 = std::min (std::max (na, nb + ish), prec_words + 1); //assert(m1<=m2 && m2<=m3 && m3<=m4 && m4<=m5); for (i = FST_M; i < m1 + FST_M; ++i) d[i] = a[i]; if(db > 0) {//Addition for (i = m1 + FST_M; i < m2 + FST_M; ++i) d[i] = a[i] + b[i-ish]; for (i = m2 + FST_M; i < m3 + FST_M; ++i) d[i] = a[i]; for (i = m3 + FST_M; i < m4 + FST_M; ++i) d[i] = 0.0; for (i = m4 + FST_M; i < m5 + FST_M; ++i) d[i] = b[i-ish]; } else {//Subtraction for (i = m1 + FST_M; i < m2 + FST_M; ++i) d[i] = a[i] - b[i-ish]; for (i = m2 + FST_M; i < m3 + FST_M; ++i) d[i] = a[i]; for (i = m3 + FST_M; i < m4 + FST_M; ++i) d[i] = 0.0; for (i = m4 + FST_M; i < m5 + FST_M; ++i) d[i] = - b[i-ish]; } nd = m5; ixd = ixa; d[nd+3] = 0.0; d[nd+4] = 0.0; } else { // B has greater exponent than A, so A must be shifted to the right // to line up the radix point. nsh = -ish; m1 = std::min (nb, nsh); m2 = std::min (nb, na + nsh); m3 = nb; m4 = std::min (std::max (nb, nsh), prec_words + 1); m5 = std::min (std::max (nb, na + nsh), prec_words + 1); //assert(m1<=m2 && m2<=m3 && m3<=m4 && m4<=m5); if(db > 0) {//Addition for (i = FST_M; i < m1 + FST_M; ++i) d[i] = b[i]; for (i = m1 + FST_M; i < m2 + FST_M; ++i) d[i] = a[i-nsh] + b[i]; for (i = m2 + FST_M; i < m3 + FST_M; ++i) d[i] = b[i]; } else {//Subtraction for (i = FST_M; i < m1 + FST_M; ++i) d[i] = - b[i]; for (i = m1 + FST_M; i < m2 + FST_M; ++i) d[i] = a[i-nsh] - b[i]; for (i = m2 + FST_M; i < m3 + FST_M; ++i) d[i] = - b[i]; } for (i = m3 + FST_M; i < m4 + FST_M; ++i) d[i] = 0.0; for (i = m4 + FST_M; i < m5 + FST_M; ++i) d[i] = a[i-nsh]; nd = m5; ixd = ixb; d[nd+3] = 0.0; d[nd+4] = 0.0; } // Call mpnorm to fix up result and store in c. d[1] = ia >= 0 ? nd : -nd; d[2] = ixd; mpnorm(d, c, prec_words); delete [] (d); if (debug_level >= 9) print_mpreal("MPADD O: c ", c); return; }
inline void reverse_cond_op( size_t d , size_t i_z , const addr_t* arg , size_t num_par , const Base* parameter , size_t nc_taylor , const Base* taylor , size_t nc_partial , Base* partial ) { Base y_0, y_1; Base zero(0); Base* pz; Base* py_2; Base* py_3; CPPAD_ASSERT_UNKNOWN( size_t(arg[0]) < static_cast<size_t> (CompareNe) ); CPPAD_ASSERT_UNKNOWN( NumArg(CExpOp) == 6 ); CPPAD_ASSERT_UNKNOWN( NumRes(CExpOp) == 1 ); CPPAD_ASSERT_UNKNOWN( arg[1] != 0 ); pz = partial + i_z * nc_partial + 0; if( arg[1] & 1 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[2]) < i_z ); y_0 = taylor[ arg[2] * nc_taylor + 0 ]; } else { CPPAD_ASSERT_UNKNOWN( size_t(arg[2]) < num_par ); y_0 = parameter[ arg[2] ]; } if( arg[1] & 2 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[3]) < i_z ); y_1 = taylor[ arg[3] * nc_taylor + 0 ]; } else { CPPAD_ASSERT_UNKNOWN( size_t(arg[3]) < num_par ); y_1 = parameter[ arg[3] ]; } if( arg[1] & 4 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[4]) < i_z ); py_2 = partial + arg[4] * nc_partial; size_t j = d + 1; while(j--) { py_2[j] += CondExpOp( CompareOp( arg[0] ), y_0, y_1, pz[j], zero ); } } if( arg[1] & 8 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[5]) < i_z ); py_3 = partial + arg[5] * nc_partial; size_t j = d + 1; while(j--) { py_3[j] += CondExpOp( CompareOp( arg[0] ), y_0, y_1, zero, pz[j] ); } } return; }
INT_PTR SettingsPublish::ProcMessage(UINT message, WPARAM wParam, LPARAM lParam) { HWND hwndTemp; switch(message) { case WM_INITDIALOG: { LocalizeWindow(hwnd); RECT serviceRect, saveToFileRect; GetWindowRect(GetDlgItem(hwnd, IDC_SERVICE), &serviceRect); GetWindowRect(GetDlgItem(hwnd, IDC_SAVEPATH), &saveToFileRect); data.fileControlOffset = saveToFileRect.top-serviceRect.top; //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_MODE); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Publish.Mode.LiveStream")); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)Str("Settings.Publish.Mode.FileOnly")); int mode = LoadSettingComboInt(hwndTemp, TEXT("Publish"), TEXT("Mode"), 0, 2); data.mode = mode; //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_SERVICE); int itemId = (int)SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)TEXT("Custom")); SendMessage(hwndTemp, CB_SETITEMDATA, itemId, 0); UINT numServices = 0; XConfig serverData; if(serverData.Open(TEXT("services.xconfig"))) { XElement *services = serverData.GetElement(TEXT("services")); if(services) { numServices = services->NumElements(); for(UINT i=0; i<numServices; i++) { XElement *service = services->GetElementByID(i); itemId = (int)SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)service->GetName()); SendMessage(hwndTemp, CB_SETITEMDATA, itemId, service->GetInt(TEXT("id"))); } } } int serviceID = AppConfig->GetInt(TEXT("Publish"), TEXT("Service"), 0); if(mode != 0) ShowWindow(hwndTemp, SW_HIDE); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_PLAYPATH); LoadSettingEditString(hwndTemp, TEXT("Publish"), TEXT("PlayPath"), NULL); if(mode != 0) ShowWindow(hwndTemp, SW_HIDE); if(serviceID == 0) //custom { ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), SW_HIDE); hwndTemp = GetDlgItem(hwnd, IDC_URL); LoadSettingEditString(hwndTemp, TEXT("Publish"), TEXT("URL"), NULL); SendDlgItemMessage(hwnd, IDC_SERVICE, CB_SETCURSEL, 0, 0); } else { ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_HIDE); hwndTemp = GetDlgItem(hwnd, IDC_SERVERLIST); XElement *services = serverData.GetElement(TEXT("services")); if(services) { XElement *service = NULL; numServices = services->NumElements(); for(UINT i=0; i<numServices; i++) { XElement *curService = services->GetElementByID(i); if(curService->GetInt(TEXT("id")) == serviceID) { SendDlgItemMessage(hwnd, IDC_SERVICE, CB_SETCURSEL, i+1, 0); service = curService; break; } } if(service) { XElement *servers = service->GetElement(TEXT("servers")); if(servers) { UINT numServers = servers->NumDataItems(); for(UINT i=0; i<numServers; i++) { XDataItem *server = servers->GetDataItemByID(i); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)server->GetName()); } } } } LoadSettingComboString(hwndTemp, TEXT("Publish"), TEXT("URL"), NULL); } if(mode != 0) ShowWindow(hwndTemp, SW_HIDE); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_LOWLATENCYMODE); BOOL bLowLatencyMode = AppConfig->GetInt(TEXT("Publish"), TEXT("LowLatencyMode"), 0); SendMessage(hwndTemp, BM_SETCHECK, bLowLatencyMode ? BST_CHECKED : BST_UNCHECKED, 0); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_AUTORECONNECT); BOOL bAutoReconnect = AppConfig->GetInt(TEXT("Publish"), TEXT("AutoReconnect"), 1); SendMessage(hwndTemp, BM_SETCHECK, bAutoReconnect ? BST_CHECKED : BST_UNCHECKED, 0); if(mode != 0) ShowWindow(hwndTemp, SW_HIDE); hwndTemp = GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT); EnableWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), bAutoReconnect); EnableWindow(hwndTemp, bAutoReconnect); int retryTime = AppConfig->GetInt(TEXT("Publish"), TEXT("AutoReconnectTimeout"), 10); if(retryTime > 60) retryTime = 60; else if(retryTime < 0) retryTime = 0; SendMessage(hwndTemp, UDM_SETRANGE32, 0, 60); SendMessage(hwndTemp, UDM_SETPOS32, 0, retryTime); if(mode != 0) ShowWindow(hwndTemp, SW_HIDE); //-------------------------------------------- hwndTemp = GetDlgItem(hwnd, IDC_DELAY); int delayTime = AppConfig->GetInt(TEXT("Publish"), TEXT("Delay"), 0); SendMessage(hwndTemp, UDM_SETRANGE32, 0, 900); SendMessage(hwndTemp, UDM_SETPOS32, 0, delayTime); //-------------------------------------------- if(mode != 0) { ShowWindow(GetDlgItem(hwnd, IDC_SERVICE_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_PLAYPATH_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_URL_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_SERVER_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_LOWLATENCYMODE), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_DELAY_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_DELAY_EDIT), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_DELAY), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), SW_HIDE); //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK), SW_HIDE); //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK_STATIC), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_SAVETOFILE), SW_HIDE); AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_BROWSE), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTSTREAM), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTRECORDING), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STOPRECORDING), 0, -data.fileControlOffset); } //-------------------------------------------- DWORD startHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StartStreamHotkey")); SendMessage(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), HKM_SETHOTKEY, startHotkey, 0); //-------------------------------------------- DWORD stopHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StopStreamHotkey")); SendMessage(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), HKM_SETHOTKEY, stopHotkey, 0); //-------------------------------------------- startHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StartRecordingHotkey")); SendMessage(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), HKM_SETHOTKEY, startHotkey, 0); //-------------------------------------------- stopHotkey = AppConfig->GetInt(TEXT("Publish"), TEXT("StopRecordingHotkey")); SendMessage(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), HKM_SETHOTKEY, stopHotkey, 0); //-------------------------------------------- BOOL bKeepRecording = AppConfig->GetInt(TEXT("Publish"), TEXT("KeepRecording")); SendMessage(GetDlgItem(hwnd, IDC_KEEPRECORDING), BM_SETCHECK, bKeepRecording ? BST_CHECKED : BST_UNCHECKED, 0); BOOL bSaveToFile = AppConfig->GetInt(TEXT("Publish"), TEXT("SaveToFile")); SendMessage(GetDlgItem(hwnd, IDC_SAVETOFILE), BM_SETCHECK, bSaveToFile ? BST_CHECKED : BST_UNCHECKED, 0); CTSTR lpSavePath = AppConfig->GetStringPtr(TEXT("Publish"), TEXT("SavePath")); SetWindowText(GetDlgItem(hwnd, IDC_SAVEPATH), lpSavePath); EnableWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), bSaveToFile || (mode != 0)); EnableWindow(GetDlgItem(hwnd, IDC_SAVEPATH), bSaveToFile || (mode != 0)); EnableWindow(GetDlgItem(hwnd, IDC_BROWSE), bSaveToFile || (mode != 0)); //-------------------------------------------- //SetWindowText(GetDlgItem(hwnd, IDC_DASHBOARDLINK), App->strDashboard); //-------------------------------------------- SetWarningInfo(); ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_HIDE); SetChangedSettings(false); return TRUE; } case WM_CTLCOLORSTATIC: { switch (GetDlgCtrlID((HWND)lParam)) { case IDC_WARNINGS: SetTextColor((HDC)wParam, RGB(255, 0, 0)); SetBkColor((HDC)wParam, COLORREF(GetSysColor(COLOR_3DFACE))); return (INT_PTR)GetSysColorBrush(COLOR_BTNFACE); } } break; case WM_DESTROY: { } break; case WM_NOTIFY: { NMHDR *nmHdr = (NMHDR*)lParam; if(nmHdr->idFrom == IDC_AUTORECONNECT_TIMEOUT) { if(nmHdr->code == UDN_DELTAPOS) SetChangedSettings(true); } break; } case WM_COMMAND: { bool bDataChanged = false; switch(LOWORD(wParam)) { case IDC_MODE: { if(HIWORD(wParam) != CBN_SELCHANGE) break; int mode = (int)SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0); int swShowControls = (mode == 0) ? SW_SHOW : SW_HIDE; ShowWindow(GetDlgItem(hwnd, IDC_SERVICE), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_PLAYPATH), swShowControls); int serviceID = (int)SendMessage(GetDlgItem(hwnd, IDC_SERVICE), CB_GETCURSEL, 0, 0); if(serviceID == 0) { ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_URL), swShowControls); } else { ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_HIDE); } BOOL bSaveToFile = SendMessage(GetDlgItem(hwnd, IDC_SAVETOFILE), BM_GETCHECK, 0, 0) != BST_UNCHECKED; EnableWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), bSaveToFile || (mode != 0)); EnableWindow(GetDlgItem(hwnd, IDC_SAVEPATH), bSaveToFile || (mode != 0)); EnableWindow(GetDlgItem(hwnd, IDC_BROWSE), bSaveToFile || (mode != 0)); if(mode == 0 && data.mode == 1) { AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH_STATIC), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_BROWSE), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY_STATIC), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY_STATIC), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTSTREAM), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY_STATIC), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY_STATIC), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTRECORDING), 0, data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STOPRECORDING), 0, data.fileControlOffset); } else if(mode == 1 && data.mode == 0) { AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_SAVEPATH), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_BROWSE), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTSTREAM), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY_STATIC), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STARTRECORDING), 0, -data.fileControlOffset); AdjustWindowPos(GetDlgItem(hwnd, IDC_CLEARHOTKEY_STOPRECORDING), 0, -data.fileControlOffset); } data.mode = mode; ShowWindow(GetDlgItem(hwnd, IDC_SERVICE_STATIC), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_PLAYPATH_STATIC), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_URL_STATIC), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_SERVER_STATIC), swShowControls); //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK), swShowControls); //ShowWindow(GetDlgItem(hwnd, IDC_DASHBOARDLINK_STATIC), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_LOWLATENCYMODE), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_STATIC), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_DELAY_STATIC), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_DELAY_EDIT), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_DELAY), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_SAVETOFILE), swShowControls); ShowWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), swShowControls); SetWarningInfo(); bDataChanged = true; break; } case IDC_SERVICE: if(HIWORD(wParam) == CBN_SELCHANGE) { int serviceID = (int)SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0); if(serviceID == 0) { ShowWindow(GetDlgItem(hwnd, IDC_SERVERLIST), SW_HIDE); ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_SHOW); SetWindowText(GetDlgItem(hwnd, IDC_URL), NULL); //SetWindowText(GetDlgItem(hwnd, IDC_DASHBOARDLINK), NULL); } else { ShowWindow(GetDlgItem(hwnd, IDC_URL), SW_HIDE); hwndTemp = GetDlgItem(hwnd, IDC_SERVERLIST); ShowWindow(hwndTemp, SW_SHOW); SendMessage(hwndTemp, CB_RESETCONTENT, 0, 0); XConfig serverData; if(serverData.Open(TEXT("services.xconfig"))) { XElement *services = serverData.GetElement(TEXT("services")); if(services) { XElement *service = services->GetElementByID(serviceID-1); if(service) { XElement *servers = service->GetElement(TEXT("servers")); if(servers) { UINT numServers = servers->NumDataItems(); for(UINT i=0; i<numServers; i++) { XDataItem *server = servers->GetDataItemByID(i); SendMessage(hwndTemp, CB_ADDSTRING, 0, (LPARAM)server->GetName()); } } } } } SendMessage(hwndTemp, CB_SETCURSEL, 0, 0); } SetWindowText(GetDlgItem(hwnd, IDC_PLAYPATH), NULL); bDataChanged = true; } SetWarningInfo(); break; case IDC_AUTORECONNECT: if(HIWORD(wParam) == BN_CLICKED) { BOOL bAutoReconnect = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED; EnableWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT), bAutoReconnect); EnableWindow(GetDlgItem(hwnd, IDC_AUTORECONNECT_TIMEOUT_EDIT), bAutoReconnect); SetChangedSettings(true); } break; case IDC_AUTORECONNECT_TIMEOUT_EDIT: if(HIWORD(wParam) == EN_CHANGE) SetChangedSettings(true); break; case IDC_DELAY_EDIT: if(HIWORD(wParam) == EN_CHANGE) bDataChanged = true; break; case IDC_SAVETOFILE: if(HIWORD(wParam) == BN_CLICKED) { BOOL bSaveToFile = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED; EnableWindow(GetDlgItem(hwnd, IDC_KEEPRECORDING), bSaveToFile); EnableWindow(GetDlgItem(hwnd, IDC_SAVEPATH), bSaveToFile); EnableWindow(GetDlgItem(hwnd, IDC_BROWSE), bSaveToFile); bDataChanged = true; } break; case IDC_KEEPRECORDING: if(HIWORD(wParam) == BN_CLICKED) { BOOL bKeepRecording = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0) == BST_CHECKED; App->bKeepRecording = bKeepRecording != 0; bDataChanged = true; } break; case IDC_BROWSE: { TCHAR lpFile[512]; OPENFILENAME ofn; zero(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hwnd; ofn.lpstrFile = lpFile; ofn.nMaxFile = 511; ofn.lpstrFile[0] = 0; ofn.lpstrFilter = TEXT("MP4 File (*.mp4)\0*.mp4\0Flash Video File (*.flv)\0*.flv\0"); ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.nFilterIndex = 1; ofn.lpstrInitialDir = AppConfig->GetStringPtr(TEXT("Publish"), TEXT("LastSaveDir")); ofn.Flags = OFN_PATHMUSTEXIST; TCHAR curDirectory[512]; GetCurrentDirectory(511, curDirectory); BOOL bChoseFile = GetSaveFileName(&ofn); SetCurrentDirectory(curDirectory); if(*lpFile && bChoseFile) { String strFile = lpFile; strFile.FindReplace(TEXT("\\"), TEXT("/")); String strExtension = GetPathExtension(strFile); if(strExtension.IsEmpty() || (!strExtension.CompareI(TEXT("flv")) && /*!strExtension.CompareI(TEXT("avi")) &&*/ !strExtension.CompareI(TEXT("mp4")))) { switch(ofn.nFilterIndex) { case 1: strFile << TEXT(".mp4"); break; case 2: strFile << TEXT(".flv"); break; /*case 3: strFile << TEXT(".avi"); break;*/ } } String strFilePath = GetPathDirectory(strFile).FindReplace(TEXT("/"), TEXT("\\")) << TEXT("\\"); AppConfig->SetString(TEXT("Publish"), TEXT("LastSaveDir"), strFilePath); strFile.FindReplace(TEXT("/"), TEXT("\\")); SetWindowText(GetDlgItem(hwnd, IDC_SAVEPATH), strFile); bDataChanged = true; } break; } case IDC_LOWLATENCYMODE: if(HIWORD(wParam) == BN_CLICKED) bDataChanged = true; break; case IDC_STARTSTREAMHOTKEY: case IDC_STOPSTREAMHOTKEY: //case IDC_DASHBOARDLINK: case IDC_STARTRECORDINGHOTKEY: case IDC_STOPRECORDINGHOTKEY: if(HIWORD(wParam) == EN_CHANGE) SetChangedSettings(true); break; case IDC_PLAYPATH: case IDC_URL: case IDC_SAVEPATH: if(HIWORD(wParam) == EN_CHANGE) bDataChanged = true; break; case IDC_CLEARHOTKEY_STARTSTREAM: if(HIWORD(wParam) == BN_CLICKED) { if(SendMessage(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), HKM_GETHOTKEY, 0, 0)) { SendMessage(GetDlgItem(hwnd, IDC_STARTSTREAMHOTKEY), HKM_SETHOTKEY, 0, 0); SetChangedSettings(true); } } break; case IDC_CLEARHOTKEY: if(HIWORD(wParam) == BN_CLICKED) { if(SendMessage(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), HKM_GETHOTKEY, 0, 0)) { SendMessage(GetDlgItem(hwnd, IDC_STOPSTREAMHOTKEY), HKM_SETHOTKEY, 0, 0); SetChangedSettings(true); } } break; case IDC_CLEARHOTKEY_STARTRECORDING: if (HIWORD(wParam) == BN_CLICKED) { if (SendMessage(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), HKM_GETHOTKEY, 0, 0)) { SendMessage(GetDlgItem(hwnd, IDC_STARTRECORDINGHOTKEY), HKM_SETHOTKEY, 0, 0); SetChangedSettings(true); } } break; case IDC_CLEARHOTKEY_STOPRECORDING: if (HIWORD(wParam) == BN_CLICKED) { if (SendMessage(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), HKM_GETHOTKEY, 0, 0)) { SendMessage(GetDlgItem(hwnd, IDC_STOPRECORDINGHOTKEY), HKM_SETHOTKEY, 0, 0); SetChangedSettings(true); } } break; case IDC_SERVERLIST: if(HIWORD(wParam) == CBN_EDITCHANGE || HIWORD(wParam) == CBN_SELCHANGE) bDataChanged = true; break; } if(bDataChanged) { ShowWindow(GetDlgItem(hwnd, IDC_INFO), SW_SHOW); SetChangedSettings(true); } break; } } return FALSE; }
inline void forward_cond_op( size_t d , size_t i_z , const addr_t* arg , size_t num_par , const Base* parameter , size_t nc_taylor , Base* taylor ) { Base y_0, y_1, y_2, y_3; Base zero(0); Base* z; CPPAD_ASSERT_UNKNOWN( size_t(arg[0]) < static_cast<size_t> (CompareNe) ); CPPAD_ASSERT_UNKNOWN( NumArg(CExpOp) == 6 ); CPPAD_ASSERT_UNKNOWN( NumRes(CExpOp) == 1 ); CPPAD_ASSERT_UNKNOWN( arg[1] != 0 ); if( arg[1] & 1 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[2]) < i_z ); y_0 = taylor[ arg[2] * nc_taylor + 0 ]; } else { CPPAD_ASSERT_UNKNOWN( size_t(arg[2]) < num_par ); y_0 = parameter[ arg[2] ]; } if( arg[1] & 2 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[3]) < i_z ); y_1 = taylor[ arg[3] * nc_taylor + 0 ]; } else { CPPAD_ASSERT_UNKNOWN( size_t(arg[3]) < num_par ); y_1 = parameter[ arg[3] ]; } # if CPPAD_USE_FORWARD0SWEEP CPPAD_ASSERT_UNKNOWN( d > 0 ); # else if( d == 0 ) { if( arg[1] & 4 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[4]) < i_z ); y_2 = taylor[ arg[4] * nc_taylor + 0 ]; } else { CPPAD_ASSERT_UNKNOWN( size_t(arg[4]) < num_par ); y_2 = parameter[ arg[4] ]; } if( arg[1] & 8 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[5]) < i_z ); y_3 = taylor[ arg[5] * nc_taylor + 0 ]; } else { CPPAD_ASSERT_UNKNOWN( size_t(arg[5]) < num_par ); y_3 = parameter[ arg[5] ]; } } else # endif { if( arg[1] & 4 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[4]) < i_z ); y_2 = taylor[ arg[4] * nc_taylor + d]; } else y_2 = zero; if( arg[1] & 8 ) { CPPAD_ASSERT_UNKNOWN( size_t(arg[5]) < i_z ); y_3 = taylor[ arg[5] * nc_taylor + d]; } else y_3 = zero; } z = taylor + i_z * nc_taylor; z[d] = CondExpOp( CompareOp( arg[0] ), y_0, y_1, y_2, y_3 ); return; }
int main(int argc, char *argv[]) { int opt; long fin = 0; int use_pkix = 0; SECStatus rv; char pbuf[1024]; PRBool crlcheck = PR_FALSE; PRBool ocspcheck = PR_FALSE; PRBool strict = PR_FALSE; CERTCertDBHandle *handle = NULL; CERTCertificate **certout = NULL; CERTVerifyLog vfy_log; CERTVerifyLog vfy_log2; CERTVerifyLog *cur_log; CERTValOutParam *pkixout = NULL; SECItem c1; SECItem c2; SECItem *certs[2]; certs[0] = &c1; certs[1] = &c2; int numcerts = 0; while ((opt = getopt(argc, argv, "u:d:e:pn:s:coSr")) != -1) { switch(opt) { /* usage type */ case 'u': set_usage(optarg); break; case 'd': db_dir = optarg; break; case 's': sub_file = optarg; break; case 'c': crlcheck = PR_TRUE; break; case 'o': ocspcheck = PR_TRUE; break; case 'S': strict = PR_TRUE; break; case 'e': end_file = optarg; break; case 'p': use_pkix = 1; break; case 'n': rightca_nick = optarg; break; case 'r': retry_verify = PR_TRUE; break; default: print_usage(); break; } } if (db_dir == NULL) db_dir = "testfiles/"; if (end_file == NULL) end_file = "testfiles/end.pem"; get_file(certs[numcerts++], end_file); if (sub_file != NULL) { get_file(certs[numcerts++], sub_file); } snprintf(pbuf, sizeof(pbuf), "sql:%s", db_dir); if (NSS_Initialize(pbuf, "", "", "secmod.db", 0x1) != SECSuccess) { printf("NSS_Initialize failed %d\n", PORT_GetError()); exit(-1); } if ((handle = CERT_GetDefaultCertDB()) == NULL) { printf("NULL handle\n"); exit(-1); } if (ocspcheck) { CERT_EnableOCSPChecking(handle); CERT_DisableOCSPDefaultResponder(handle); if (strict) CERT_SetOCSPFailureMode(ocspMode_FailureIsNotAVerificationFailure); } rv = CERT_ImportCerts(handle, 0, numcerts, certs, &certout, PR_FALSE, PR_FALSE, NULL); if (rv != SECSuccess) { printf("CERT_ImportCerts failed %d\n", PORT_GetError()); exit(-1); } vfy_log.count = 0; vfy_log.head = NULL; vfy_log.tail = NULL; vfy_log.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); vfy_log2.count = 0; vfy_log2.head = NULL; vfy_log2.tail = NULL; vfy_log2.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (use_pkix) { int in_idx = 0; CERTValInParam cvin[7]; CERTValOutParam cvout[3]; CERTCertList *trustcl = NULL; CERTRevocationFlags rev; PRUint64 revFlagsLeaf[2] = { 0, 0 }; PRUint64 revFlagsChain[2] = { 0, 0 }; zero(&cvin); /* ??? is this reasonable? */ zero(&cvout); /* ??? is this reasonable? */ zero(&rev); /* ??? is this reasonable? */ if (rightca_nick == NULL) rightca_nick = "root"; if ((trustcl = get_trust_certlist(handle, rightca_nick)) == NULL) { printf("Couldn't find trust anchor\n"); exit(-1); } cvin[in_idx].type = cert_pi_useAIACertFetch; cvin[in_idx++].value.scalar.b = PR_TRUE; cvin[in_idx].type = cert_pi_revocationFlags; cvin[in_idx++].value.pointer.revocation = &rev; cvin[in_idx].type = cert_pi_trustAnchors; cvin[in_idx++].value.pointer.chain = trustcl; cvin[in_idx].type = cert_pi_useOnlyTrustAnchors; cvin[in_idx++].value.scalar.b = PR_TRUE; set_rev_per_meth(&rev, revFlagsLeaf, revFlagsChain); set_rev_params(&rev, crlcheck, ocspcheck, strict); cvin[in_idx].type = cert_pi_end; cvout[0].type = cert_po_errorLog; cvout[0].value.pointer.log = &vfy_log; cur_log = &vfy_log; cvout[1].type = cert_po_certList; cvout[1].value.pointer.chain = NULL; cvout[2].type = cert_po_end; pkixout = &cvout[0]; pkixredo: rv = CERT_PKIXVerifyCert(*certout, pkixusage, cvin, cvout, NULL); //CERT_DestroyCertList(trustcl); } else { cur_log = &vfy_log; vfyredo: rv = CERT_VerifyCert(handle, *certout, PR_TRUE, usage, PR_Now(), NULL, cur_log); } if (rv != SECSuccess || cur_log->count > 0) { if (cur_log->count > 0 && cur_log->head != NULL) { fin = err_stat(cur_log->head); } else { fin = PORT_GetError(); } if (fin == SEC_ERROR_INADEQUATE_KEY_USAGE) { printf("SEC_ERROR_INADEQUATE_KEY_USAGE : Certificate key usage inadequate for attempted operation.\n" ); } else if (fin == SEC_ERROR_INADEQUATE_CERT_TYPE) { printf("SEC_ERROR_INADEQUATE_CERT_TYPE : Certificate type not approved for application.\n" ); } else { printf("OTHER : %ld", fin); } } if ((fin == SEC_ERROR_INADEQUATE_CERT_TYPE || fin == SEC_ERROR_INADEQUATE_KEY_USAGE) && retry_verify && !retried) { printf("Retrying verification\n"); fin = 0; retried = PR_TRUE; if (use_pkix) { pkixout[0].value.pointer.log = &vfy_log2; cur_log = &vfy_log2; pkixout[1].value.pointer.chain = NULL; if (pkixusage == certificateUsageSSLClient) { pkixusage = certificateUsageSSLServer; } else { pkixusage = certificateUsageSSLClient; } goto pkixredo; } else { if (usage == certUsageSSLClient) { usage = certUsageSSLServer; } else { usage = certUsageSSLClient; } goto vfyredo; } } PORT_FreeArena(vfy_log.arena, PR_FALSE); PORT_FreeArena(vfy_log2.arena, PR_FALSE); NSS_Shutdown(); exit(fin == 0 ? 0 : 1); }
inline bool is_zero() const { return *this == zero(); }
void GraphicsCaptureSource::Render(const Vect2 &pos, const Vect2 &size) { if(capture) { Shader *lastShader = GetCurrentPixelShader(); float fGamma = float(-(gamma-100) + 100) * 0.01f; LoadPixelShader(drawShader); HANDLE hGamma = drawShader->GetParameterByName(TEXT("gamma")); if(hGamma) drawShader->SetFloat(hGamma, fGamma); //---------------------------------------------------------- // capture mouse bMouseCaptured = false; if(bCaptureMouse) { CURSORINFO ci; zero(&ci, sizeof(ci)); ci.cbSize = sizeof(ci); if(GetCursorInfo(&ci) && hwndCapture) { mcpy(&cursorPos, &ci.ptScreenPos, sizeof(cursorPos)); ScreenToClient(hwndCapture, &cursorPos); if(ci.flags & CURSOR_SHOWING) { if(ci.hCursor == hCurrentCursor) bMouseCaptured = true; else { HICON hIcon = CopyIcon(ci.hCursor); hCurrentCursor = ci.hCursor; delete cursorTexture; cursorTexture = NULL; if(hIcon) { ICONINFO ii; if(GetIconInfo(hIcon, &ii)) { xHotspot = int(ii.xHotspot); yHotspot = int(ii.yHotspot); UINT size; LPBYTE lpData = GetCursorData(hIcon, ii, size); if(lpData) { cursorTexture = CreateTexture(size, size, GS_BGRA, lpData, FALSE); if(cursorTexture) bMouseCaptured = true; Free(lpData); } DeleteObject(ii.hbmColor); DeleteObject(ii.hbmMask); } DestroyIcon(hIcon); } } } } } //---------------------------------------------------------- // game texture Texture *tex = capture->LockTexture(); Vect2 texPos = Vect2(0.0f, 0.0f); Vect2 texStretch = Vect2(1.0f, 1.0f); if(tex) { Vect2 texSize = Vect2(float(tex->Width()), float(tex->Height())); Vect2 totalSize = API->GetBaseSize(); Vect2 center = totalSize*0.5f; BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO); if(bStretch) { if(bIgnoreAspect) texStretch *= totalSize; else { float xDif = fabsf(totalSize.x-texSize.x); float yDif = fabsf(totalSize.y-texSize.y); float multiplyVal = (xDif < yDif) ? (totalSize.x/texSize.x) : (totalSize.y/texSize.y); texStretch *= texSize*multiplyVal; texPos = center-(texStretch*0.5f); } } else { texStretch *= texSize; texPos = center-(texStretch*0.5f); } Vect2 sizeAdjust = size/totalSize; texPos *= sizeAdjust; texPos += pos; texStretch *= sizeAdjust; RoundVect2(texPos); RoundVect2(texSize); if(bFlip) DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y+texStretch.y, texPos.x+texStretch.x, texPos.y); else DrawSprite(tex, 0xFFFFFFFF, texPos.x, texPos.y, texPos.x+texStretch.x, texPos.y+texStretch.y); capture->UnlockTexture(); BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA); //---------------------------------------------------------- // draw mouse if(bMouseCaptured && cursorTexture) { Vect2 newCursorPos = Vect2(float(cursorPos.x-xHotspot), float(cursorPos.y-xHotspot)); Vect2 newCursorSize = Vect2(float(cursorTexture->Width()), float(cursorTexture->Height())); newCursorPos /= texSize; newCursorSize /= texSize; newCursorPos *= texStretch; newCursorPos += texPos; newCursorSize *= texStretch; bool bInvertCursor = false; if(invertShader) { if(bInvertCursor = ((GetAsyncKeyState(VK_LBUTTON) & 0x8000) != 0 || (GetAsyncKeyState(VK_RBUTTON) & 0x8000) != 0)) LoadPixelShader(invertShader); } DrawSprite(cursorTexture, 0xFFFFFFFF, newCursorPos.x, newCursorPos.y+newCursorSize.y, newCursorPos.x+newCursorSize.x, newCursorPos.y); } } if(lastShader) LoadPixelShader(lastShader); } }
STHDRImage* recover_hdr(vector<Photo>& photos, CameraResponse& response) { int width,height; STImage *tmpImage = new STImage(photos[0].filename); width = tmpImage->GetWidth(); height = tmpImage->GetHeight(); delete tmpImage; STHDRImage *newImage = new STHDRImage(width,height); vector< vector<STColor3f> > Ls; vector< vector<STColor3f> > ws; vector< vector<STColor3f> > Lw; for (int i=0;i<width;i++) { vector<STColor3f> row; for (int j=0;j<height;j++) { STColor3f zero(0); row.push_back(zero); } Ls.push_back(row); ws.push_back(row); Lw.push_back(row); } for (int k=0;k<photos.size();k++) { //open photo STImage currentImage(photos[k].filename); //perform calculations for (int i=0;i<width;i++) { for (int j=0;j<height;j++) { STColor4ub currentPixel = currentImage.GetPixel(i, j); Ls[i][j].r += (response.Weight(currentPixel).r * (response.GetExposure(currentPixel).r - logf(photos[k].shutter) ) ); Ls[i][j].g += (response.Weight(currentPixel).g * (response.GetExposure(currentPixel).g - logf(photos[k].shutter) ) ); Ls[i][j].b += (response.Weight(currentPixel).b * (response.GetExposure(currentPixel).b - logf(photos[k].shutter) ) ); ws[i][j] += response.Weight(currentPixel); } } for (int i=0;i<width;i++) { for (int j=0;j<height;j++) { Lw[i][j].r = expf(Ls[i][j].r / ws[i][j].r); Lw[i][j].g = expf(Ls[i][j].g / ws[i][j].g); Lw[i][j].b = expf(Ls[i][j].b / ws[i][j].b); newImage->SetPixel(i, j, Lw[i][j]); } } } return newImage; }
/** * Maximum entropy estimate by autocorrelation method. Implements * Yule-Walker method. * * @param r * Vector of correlation coefficients. * @param n * Number of lags used by MEM algorithm. * @param nfft * Size of fft for display. * @param spect * REAL*4 array of length FFT_SIZE in which the spectrum is returned. * @param errmsg * ERROR_MESSAGE CHARACTER*130 variable containing error message if an * an error occurs, ' ' otherwise. * @param errmsg_s * Length of \p errmsg * @param aux * REAL*4 scratch array of length FFT_SIZE. * * @author David Harris * * @date December 28, 1984 Last Modified * */ void mem(float *r, int n, int nfft, float *spect, char *errmsg, int errmsg_s, float *aux) { int i; float scale; float *a, *reflct; float *A; float *const Aux = &aux[0] - 1; float *const R = &r[0] - 1; float *const Spect = &spect[0] - 1; UNUSED(errmsg_s); if((a = (float *)malloc(n*sizeof(float))) == NULL){ strcpy(errmsg, "error allocating memory--mem\n"); return; } if((reflct = (float *)malloc(n*sizeof(float))) == NULL){ strcpy(errmsg, "error allocating memory--mem\n"); free(a); return; } A = a-1; /* if( n > 100 ){ fstrncpy( errmsg, errmsg_s-1, "MEM *** Maximum order (100) exceeded ***" , 40 ); return; } */ /* Zero arrays * */ zero( spect, nfft ); zero( aux, nfft ); /* Invoke Levinson's recursion to compute prediction filter * */ levin( r, a, reflct, n ); /* Compute transfer function of prediction filter * */ for( i = 1; i <= n; i++ ) Spect[i] = A[i]; fft( spect, aux, nfft, -1 ); /* Spectral estimate is reciprocal of filter's power spectrum * * Scale factor is equal to prediction error * */ scale = 0.; for( i = 1; i <= n; i++ ) scale = scale + R[i]*A[i]; for( i = 1; i <= nfft; i++ ) Spect[i] = scale/(powi(Spect[i],2) + powi(Aux[i],2)); /* Bye * */ free(a); free(reflct); return; } /* end of function */
static int test_option_status(sd_event *e) { uint8_t option1[] = { /* IA NA */ 0x00, 0x03, 0x00, 0x12, 0x1a, 0x1d, 0x1a, 0x1d, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, /* status option */ 0x00, 0x0d, 0x00, 0x02, 0x00, 0x01, }; static const uint8_t option2[] = { /* IA NA */ 0x00, 0x03, 0x00, 0x2e, 0x1a, 0x1d, 0x1a, 0x1d, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, /* IA Addr */ 0x00, 0x05, 0x00, 0x1e, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x01, 0x02, 0x03, 0x04, 0x0a, 0x0b, 0x0c, 0x0d, /* status option */ 0x00, 0x0d, 0x00, 0x02, 0x00, 0x01, }; static const uint8_t option3[] = { /* IA NA */ 0x00, 0x03, 0x00, 0x34, 0x1a, 0x1d, 0x1a, 0x1d, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, /* IA Addr */ 0x00, 0x05, 0x00, 0x24, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x01, 0x02, 0x03, 0x04, 0x0a, 0x0b, 0x0c, 0x0d, /* status option */ 0x00, 0x0d, 0x00, 0x08, 0x00, 0x00, 'f', 'o', 'o', 'b', 'a', 'r', }; static const uint8_t option4[] = { /* IA PD */ 0x00, 0x19, 0x00, 0x2f, 0x1a, 0x1d, 0x1a, 0x1d, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, /* IA PD Prefix */ 0x00, 0x1a, 0x00, 0x1f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x80, 0x20, 0x01, 0x0d, 0xb8, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* status option */ 0x00, 0x0d, 0x00, 0x02, 0x00, 0x00, }; static const uint8_t option5[] = { /* IA PD */ 0x00, 0x19, 0x00, 0x52, 0x1a, 0x1d, 0x1a, 0x1d, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x02, /* IA PD Prefix #1 */ 0x00, 0x1a, 0x00, 0x1f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x80, 0x20, 0x01, 0x0d, 0xb8, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* status option */ 0x00, 0x0d, 0x00, 0x02, 0x00, 0x00, /* IA PD Prefix #2 */ 0x00, 0x1a, 0x00, 0x1f, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x80, 0x20, 0x01, 0x0d, 0xb8, 0xc0, 0x0l, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x02, 0x00, 0x00, }; DHCP6Option *option; DHCP6IA ia, pd; int r = 0; if (verbose) printf("* %s\n", __FUNCTION__); zero(ia); option = (DHCP6Option *)option1; assert_se(sizeof(option1) == sizeof(DHCP6Option) + be16toh(option->len)); r = dhcp6_option_parse_ia(option, &ia); assert_se(r == -EINVAL); assert_se(ia.addresses == NULL); option->len = htobe16(17); r = dhcp6_option_parse_ia(option, &ia); assert_se(r == -ENOBUFS); assert_se(ia.addresses == NULL); option->len = htobe16(sizeof(DHCP6Option)); r = dhcp6_option_parse_ia(option, &ia); assert_se(r == -ENOBUFS); assert_se(ia.addresses == NULL); zero(ia); option = (DHCP6Option *)option2; assert_se(sizeof(option2) == sizeof(DHCP6Option) + be16toh(option->len)); r = dhcp6_option_parse_ia(option, &ia); assert_se(r >= 0); assert_se(ia.addresses == NULL); zero(ia); option = (DHCP6Option *)option3; assert_se(sizeof(option3) == sizeof(DHCP6Option) + be16toh(option->len)); r = dhcp6_option_parse_ia(option, &ia); assert_se(r >= 0); assert_se(ia.addresses != NULL); dhcp6_lease_free_ia(&ia); zero(pd); option = (DHCP6Option *)option4; assert_se(sizeof(option4) == sizeof(DHCP6Option) + be16toh(option->len)); r = dhcp6_option_parse_ia(option, &pd); assert_se(r == 0); assert_se(pd.addresses != NULL); assert_se(memcmp(&pd.ia_pd.id, &option4[4], 4) == 0); assert_se(memcmp(&pd.ia_pd.lifetime_t1, &option4[8], 4) == 0); assert_se(memcmp(&pd.ia_pd.lifetime_t2, &option4[12], 4) == 0); dhcp6_lease_free_ia(&pd); zero(pd); option = (DHCP6Option *)option5; assert_se(sizeof(option5) == sizeof(DHCP6Option) + be16toh(option->len)); r = dhcp6_option_parse_ia(option, &pd); assert_se(r == 0); assert_se(pd.addresses != NULL); dhcp6_lease_free_ia(&pd); return 0; }
void build(_MIPD_ flash x,int (*gen)(_MIPT_ big,int)) { /* Build x from its regular c.f. * * generated by gen() */ mr_small ex1,ex2,ex,st,sr; int a,b,c,d,rm,q,n,prc,lw2,lw4,lz; BOOL finoff,last; big t; #ifdef MR_OS_THREADS miracl *mr_mip=get_mip(); #endif if (mr_mip->ERNUM) return; MR_IN(48) zero(mr_mip->w1); convert(_MIPP_ 1,mr_mip->w2); convert(_MIPP_ 1,mr_mip->w3); zero(mr_mip->w4); finoff=FALSE; last=FALSE; n=0; q=(*gen)(_MIPP_ x,n); /* Note - first quotient may be zero */ ex=mr_mip->base-1; if (mr_mip->nib==mr_mip->workprec) prc=mr_mip->nib; else prc=mr_mip->workprec+1; while (!mr_mip->ERNUM && q>=0) { if (q==MR_TOOBIG || n==0 || finoff) { if (q!=MR_TOOBIG) convert(_MIPP_ q,x); else last=FALSE; mr_mip->check=OFF; multiply(_MIPP_ mr_mip->w2,x,mr_mip->w0); subtract(_MIPP_ mr_mip->w1,mr_mip->w0,mr_mip->w7); mr_mip->check=ON; if ((int)(mr_mip->w7->len&MR_OBITS)>mr_mip->nib) break; copy(mr_mip->w7,mr_mip->w1); t=mr_mip->w1,mr_mip->w1=mr_mip->w2,mr_mip->w2=t; /* swap(w1,w2) */ mr_mip->check=OFF; multiply(_MIPP_ mr_mip->w4,x,mr_mip->w0); subtract(_MIPP_ mr_mip->w3,mr_mip->w0,mr_mip->w7); mr_mip->check=ON; if ((int)(mr_mip->w7->len&MR_OBITS)>mr_mip->nib) { /* oops! */ fpack(_MIPP_ mr_mip->w1,mr_mip->w4,x); negify(x,x); mr_mip->EXACT=FALSE; MR_OUT return; } copy(mr_mip->w7,mr_mip->w3); t=mr_mip->w3,mr_mip->w3=mr_mip->w4,mr_mip->w4=t; /* swap(w3,w4) */ n++; } lw2=(int)(mr_mip->w2->len&MR_OBITS); lw4=(int)(mr_mip->w4->len&MR_OBITS); lz=lw2+lw4; if (lz > prc) break; /* too big - exit */ if (last) { if (finoff) break; finoff=TRUE; q=(*gen)(_MIPP_ x,n); continue; } if (lz>=prc-1) { /* nearly finished - so be careful not to overshoot */ if (mr_mip->base==0) { #ifndef MR_NOFULLWIDTH st=mr_mip->w2->w[lw2-1]+1; if (st==0) ex1=1; else ex1=muldvm((mr_small)1,(mr_small)0,st,&sr); st=mr_mip->w4->w[lw4-1]+1; if (st==0) ex2=1; else ex2=muldvm((mr_small)1,(mr_small)0,st,&sr); #endif } else { ex1=mr_mip->base/(mr_mip->w2->w[lw2-1]+1); ex2=mr_mip->base/(mr_mip->w4->w[lw4-1]+1); } if (ex2>ex1) ex=ex1,ex1=ex2,ex2=ex; if (lz==prc) ex=ex2; else ex=ex1; last=TRUE; } a=1; b=0; c=0; d=1; forever { q=(*gen)(_MIPP_ x,n); if (q<0 || q>=MR_TOOBIG/mr_abs(d)) { /* there could be more.... *** V3.21 mod *** */ last=FALSE; break; } rm=b-q*d; b=d; d=rm; rm=a-q*c; a=c; c=rm; n++; if ((mr_small)(mr_abs(c-d))>ex) break; } premult(_MIPP_ mr_mip->w1,c,mr_mip->w7); premult(_MIPP_ mr_mip->w1,a,mr_mip->w1); premult(_MIPP_ mr_mip->w2,b,mr_mip->w0); premult(_MIPP_ mr_mip->w2,d,mr_mip->w2); add(_MIPP_ mr_mip->w1,mr_mip->w0,mr_mip->w1); add(_MIPP_ mr_mip->w2,mr_mip->w7,mr_mip->w2); premult(_MIPP_ mr_mip->w3,c,mr_mip->w7); premult(_MIPP_ mr_mip->w3,a,mr_mip->w3); premult(_MIPP_ mr_mip->w4,b,mr_mip->w0); premult(_MIPP_ mr_mip->w4,d,mr_mip->w4); add(_MIPP_ mr_mip->w3,mr_mip->w0,mr_mip->w3); add(_MIPP_ mr_mip->w4,mr_mip->w7,mr_mip->w4); }
/// constructors Location_Class::Location_Class() { zero(); }
RTColor RTRayTracer::traceRay(RTRay &ray, int depth, RTLight light) { RTColor color(135,206,250); if(depth>scene.getMaxDepth()) { RTColor zero(0,0,0); return zero; //BLACK } std::vector<RTObject*> objects = this->scene.getPrimitives(); RTObject *closestObject=NULL; RTVector hitPoint,closestPoint; double t,nearest=INF; //percorre objetos da cena for(unsigned int io=0; io<objects.size(); io++) { //testa a inte rseção if(!objects[io]->intersect(ray,t)) continue; else { //hit hitPoint = ray.getPos()+(ray.getDir()*t); t= hitPoint.getNorma(); if(t<nearest) { nearest = t; closestObject=objects[io]; closestPoint=hitPoint; } } } if(nearest==INF) { //nao intersecionou return color; } RTColor reflectColor,refracColor,objColor; int surfaceType=closestObject->getBrdf()->getSurfaceType(); double fogFactor=0; //verifica se existe fog na cena if(scene.getHasFog()) { //calcula o fator fog fogFactor=(scene.getFog().getZ_end()-closestPoint.getZ())/(scene.getFog().getZ_end()-scene.getFog().getZ_start()); fogFactor=(fogFactor>1.0)?1.0:((fogFactor<0)?0:fogFactor); //clamp //fogFactor=pow(M_E,-scene.getFog().getDensity()*closestPoint.getZ()); } objColor= shading(closestObject, closestPoint, light); double reflectivePercentage = closestObject->getBrdf()->getKr(); double refractivePercentage = 0; bool isInside=false; double refraIndex=closestObject->getBrdf()->getRefracIndex(); if(surfaceType==REFLECTIVE||surfaceType==REFRACTIVE) { RTVector eyedir = -((ray.getPos()*1)-closestPoint); //d eyedir.normalize(); RTVector normal = closestObject->normalOfHitPoint(closestPoint);//N if(surfaceType==REFRACTIVE) { //aplica fresnel if(closestObject->getObjTag()==SPHERE) { //verifica se o raio de refração segue para dentro da esfera RTSphere *sp= dynamic_cast<RTSphere*>(closestObject); double centerDist =sqrt(pow(ray.getPos().getX() - sp->getCenter().getX(), 2) + pow(ray.getPos().getY() - sp->getCenter().getY(), 2) + pow(ray.getPos().getZ() - sp->getCenter().getZ(), 2)); isInside=(centerDist<sp->getRadius()); } reflectivePercentage=FresnelTerm(eyedir,normal,refraIndex,isInside); //R refractivePercentage=1-reflectivePercentage; //(1-R) } if(reflectivePercentage>0) { //calcula reflexão RTRay reflectionRay=genReflectionRay(eyedir,normal,closestPoint); reflectColor=(traceRay(reflectionRay,depth+1,light)); } if(refractivePercentage>0) { double refraIndex=closestObject->getBrdf()->getRefracIndex(); RTRay refracRay=genRefractRay(eyedir,normal,closestPoint,refraIndex,isInside); refracColor=(traceRay(refracRay,depth+1,light)); } } if(surfaceType==REFRACTIVE&&!isInside) { color=reflectColor*reflectivePercentage+refracColor*(refractivePercentage); } else { int kloc=(surfaceType==REFRACTIVE)?0:1; color=reflectColor*reflectivePercentage+refracColor*refraIndex+objColor*kloc; color=color/(reflectivePercentage+refractivePercentage+kloc); } if(scene.getHasFog()) color=(color*fogFactor)+(scene.getFog().getFogColor()*((1-fogFactor))); return color; }
clsparseStatus cg(cldenseVectorPrivate *pX, const clsparseCsrMatrixPrivate* pA, const cldenseVectorPrivate *pB, PTYPE& M, clSParseSolverControl solverControl, clsparseControl control) { assert( pA->num_cols == pB->num_values ); assert( pA->num_rows == pX->num_values ); if( ( pA->num_cols != pB->num_values ) || ( pA->num_rows != pX->num_values ) ) { return clsparseInvalidSystemSize; } //opaque input parameters with clsparse::array type; clsparse::vector<T> x(control, pX->values, pX->num_values); clsparse::vector<T> b(control, pB->values, pB->num_values); cl_int status; T scalarOne = 1; T scalarZero = 0; //clsparse::vector<T> norm_b(control, 1, 0, CL_MEM_WRITE_ONLY, true); clsparse::scalar<T> norm_b(control, 0, CL_MEM_WRITE_ONLY, false); //norm of rhs of equation status = Norm1<T>(norm_b, b, control); CLSPARSE_V(status, "Norm B Failed"); //norm_b is calculated once T h_norm_b = norm_b[0]; #ifndef NDEBUG std::cout << "norm_b " << h_norm_b << std::endl; #endif if (h_norm_b == 0) //special case b is zero so solution is x = 0 { solverControl->nIters = 0; solverControl->absoluteTolerance = 0.0; solverControl->relativeTolerance = 0.0; //we can either fill the x with zeros or cpy b to x; x = b; return clsparseSuccess; } //continuing "normal" execution of cg algorithm const auto N = pA->num_cols; //helper containers, all need to be zeroed clsparse::vector<T> y(control, N, 0, CL_MEM_READ_WRITE, true); clsparse::vector<T> z(control, N, 0, CL_MEM_READ_WRITE, true); clsparse::vector<T> r(control, N, 0, CL_MEM_READ_WRITE, true); clsparse::vector<T> p(control, N, 0, CL_MEM_READ_WRITE, true); clsparse::scalar<T> one(control, 1, CL_MEM_READ_ONLY, true); clsparse::scalar<T> zero(control, 0, CL_MEM_READ_ONLY, true); // y = A*x status = csrmv<T>(one, pA, x, zero, y, control); CLSPARSE_V(status, "csrmv Failed"); //r = b - y status = r.sub(b, y, control); //status = elementwise_transform<T, EW_MINUS>(r, b, y, control); CLSPARSE_V(status, "b - y Failed"); clsparse::scalar<T> norm_r(control, 0, CL_MEM_WRITE_ONLY, false); status = Norm1<T>(norm_r, r, control); CLSPARSE_V(status, "norm r Failed"); //T residuum = 0; clsparse::scalar<T> residuum(control, 0, CL_MEM_WRITE_ONLY, false); //residuum = norm_r[0] / h_norm_b; residuum.div(norm_r, norm_b, control); solverControl->initialResidual = residuum[0]; #ifndef NDEBUG std::cout << "initial residuum = " << solverControl->initialResidual << std::endl; #endif if (solverControl->finished(solverControl->initialResidual)) { solverControl->nIters = 0; return clsparseSuccess; } //apply preconditioner z = M*r M(r, z, control); //copy inital z to p p = z; //rz = <r, z>, here actually should be conjugate(r)) but we do not support complex type. clsparse::scalar<T> rz(control, 0, CL_MEM_WRITE_ONLY, false); status = dot<T>(rz, r, z, control); CLSPARSE_V(status, "<r, z> Failed"); int iteration = 0; bool converged = false; clsparse::scalar<T> alpha (control, 0, CL_MEM_READ_WRITE, false); clsparse::scalar<T> beta (control, 0, CL_MEM_READ_WRITE, false); //yp buffer for inner product of y and p vectors; clsparse::scalar<T> yp(control, 0, CL_MEM_WRITE_ONLY, false); clsparse::scalar<T> rz_old(control, 0, CL_MEM_WRITE_ONLY, false); while(!converged) { solverControl->nIters = iteration; //y = A*p status = csrmv<T>(one, pA, p, zero, y, control); CLSPARSE_V(status, "csrmv Failed"); status = dot<T>(yp, y, p, control); CLSPARSE_V(status, "<y,p> Failed"); // alpha = <r,z> / <y,p> //alpha[0] = rz[0] / yp[0]; alpha.div(rz, yp, control); #ifndef NDEBUG std::cout << "alpha = " << alpha[0] << std::endl; #endif //x = x + alpha*p status = axpy<T>(x, alpha, p, x, control); CLSPARSE_V(status, "x = x + alpha * p Failed"); //r = r - alpha * y; status = axpy<T, EW_MINUS>(r, alpha, y, r, control); CLSPARSE_V(status, "r = r - alpha * y Failed"); //apply preconditioner z = M*r M(r, z, control); //store old value of rz //improve that by move or swap rz_old = rz; //rz = <r,z> status = dot<T>(rz, r, z, control); CLSPARSE_V(status, "<r,z> Failed"); // beta = <r^(i), r^(i)>/<r^(i-1),r^(i-1)> // i: iteration index; // beta is ratio of dot product in current iteration compared //beta[0] = rz[0] / rz_old[0]; beta.div(rz, rz_old, control); #ifndef NDEBUG std::cout << "beta = " << beta[0] << std::endl; #endif //p = z + beta*p; status = axpby<T>(p, one, z, beta, p, control ); CLSPARSE_V(status, "p = z + beta*p Failed"); //calculate norm of r status = Norm1<T>(norm_r, r, control); CLSPARSE_V(status, "norm r Failed"); //residuum = norm_r[0] / h_norm_b; status = residuum.div(norm_r, norm_b, control); CLSPARSE_V(status, "residuum"); iteration++; converged = solverControl->finished(residuum[0]); solverControl->print(); } return clsparseSuccess; }
void dca_upmix (sample_t * samples, int acmod, int output) { switch (CONVERT (acmod, output & DCA_CHANNEL_MASK)) { case CONVERT (DCA_3F2R, DCA_MONO): zero (samples + 1024); case CONVERT (DCA_3F1R, DCA_MONO): case CONVERT (DCA_2F2R, DCA_MONO): zero (samples + 768); case CONVERT (DCA_3F, DCA_MONO): case CONVERT (DCA_2F1R, DCA_MONO): zero (samples + 512); case CONVERT (DCA_CHANNEL, DCA_MONO): case CONVERT (DCA_STEREO, DCA_MONO): zero (samples + 256); break; case CONVERT (DCA_3F2R, DCA_STEREO): case CONVERT (DCA_3F2R, DCA_DOLBY): zero (samples + 1024); case CONVERT (DCA_3F1R, DCA_STEREO): case CONVERT (DCA_3F1R, DCA_DOLBY): zero (samples + 768); case CONVERT (DCA_3F, DCA_STEREO): case CONVERT (DCA_3F, DCA_DOLBY): mix_3to2: memcpy (samples + 512, samples + 256, 256 * sizeof (sample_t)); zero (samples + 256); break; case CONVERT (DCA_2F2R, DCA_STEREO): case CONVERT (DCA_2F2R, DCA_DOLBY): zero (samples + 768); case CONVERT (DCA_2F1R, DCA_STEREO): case CONVERT (DCA_2F1R, DCA_DOLBY): zero (samples + 512); break; case CONVERT (DCA_3F2R, DCA_3F): zero (samples + 1024); case CONVERT (DCA_3F1R, DCA_3F): case CONVERT (DCA_2F2R, DCA_2F1R): zero (samples + 768); break; case CONVERT (DCA_3F2R, DCA_3F1R): zero (samples + 1024); break; case CONVERT (DCA_3F2R, DCA_2F1R): zero (samples + 1024); case CONVERT (DCA_3F1R, DCA_2F1R): mix_31to21: memcpy (samples + 768, samples + 512, 256 * sizeof (sample_t)); goto mix_3to2; case CONVERT (DCA_3F2R, DCA_2F2R): memcpy (samples + 1024, samples + 768, 256 * sizeof (sample_t)); goto mix_31to21; } }
bool kepler_orbit_circular(const struct kepler_elements *elements) { return zero(elements->eccentricity); }