int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; // // if (!m_wndToolBar.Create(this) || // !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) // { // TRACE0("Failed to create toolbar\n"); // return -1; // fail to create // } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } //pCLog = NULL; // TODO: Remove this if you don't want tool tips or a resizeable toolbar // m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() | // CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); // if (!m_buttonbar.Create(this,IDD_DIALOGBAR1, CBRS_TOP, IDD_DIALOGBAR1)) // { // return -1; // } if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } // m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); // EnableDocking(CBRS_ALIGN_ANY); // DockControlBar(&m_wndToolBar); if (!m_wndMyBar1.Create(_T("控制条"), this, CSize(280,100),TRUE,123)) { TRACE0("Failed to create mybar\n"); return -1; } if (!m_wndMyBar2.Create(_T("我的控制条2"), this,CSize(200,30),TRUE,124)) { TRACE0("Failed to create mybar\n"); return -1; } if (!m_wndLogBar3.Create(_T("输出窗口"), this,CSize(100,250),TRUE,124)) { TRACE0("Failed to create mybar\n"); return -1; } // TODO: Delete these three lines if you don't want the toolbar to // be dockable m_wndToolBar.SetButtonText(0," Optim "); m_wndToolBar.SetButtonText(1," Exit "); /////////////调整工具条///////////////// CRect rc(0, 0, 0, 0); CSize sizeMax(0, 0); CToolBarCtrl& bar = m_wndToolBar.GetToolBarCtrl(); for (int nIndex = bar.GetButtonCount() - 1; nIndex >= 0; nIndex--) { bar.GetItemRect(nIndex, rc); rc.NormalizeRect(); sizeMax.cx = __max(rc.Size().cx, sizeMax.cx); sizeMax.cy = __max(rc.Size().cy, sizeMax.cy); } //sizeMax.cx += 10; m_wndToolBar.SetSizes(sizeMax, CSize(16,15)); ////////////创建TAB Control,并把它加入到ControlBar中 /// 需要注意的是:同一个ControlBar只能加入一个"一级子窗口" // m_TabCtrl.Create(TCS_DOWN|WS_CHILD|WS_VISIBLE,CRect(0,0,100,100),&m_wndMyBar1,125); /////////////这一段代码创建树型控件//////////// // if (!m_wndTree.Create(WS_CHILD|WS_VISIBLE| // TVS_HASLINES|TVS_HASBUTTONS|TVS_LINESATROOT, // CRect(0, 0, 0, 0), &m_TabCtrl, IDC_MYTREECTRL)) // { // TRACE0("Failed to create instant bar child\n"); // return -1; // } // m_wndTree.ModifyStyleEx(0, WS_EX_CLIENTEDGE); ///往树型控件添加内容 // HTREEITEM hti = m_wndTree.InsertItem(_T("函数名")); // m_wndTree.InsertItem(_T("2")); // m_wndTree.InsertItem(_T("main()"), hti); // m_wndTree.InsertItem(_T("aaa"), hti); ///将树型控件加入到TabCtrl中 // m_TabCtrl.AddPage(&m_wndTree,"函数",IDI_ICON1); // m_TabCtrl.AddPage(RUNTIME_CLASS(CViewFunDlg),IDD_DIALOGBAR2,"第1页",IDI_ICON1); // m_TabCtrl.AddPage(RUNTIME_CLASS(CViewDlg),IDD_DIALOG2,"第三页",IDI_ICON1); // m_TabCtrl.UpdateWindow(); ////////对话框/////////// if(!dlg.Create(IDD_DIALOGBAR2,&m_wndMyBar1)) return -1; dlg.ShowWindow(SW_SHOW); if(!m_commandDlg.Create(IDD_COMMAND,&m_wndMyBar2)) return -1; m_commandDlg.ShowWindow(SW_SHOW); if(!m_log.Create(IDD_DIALOGBAR3,&m_wndLogBar3)) return -1; m_log.ShowWindow(SW_SHOW); // m_listFun.Create( // WS_CHILD|WS_VISIBLE|WS_BORDER|LVS_REPORT, // CRect(10,10,400,200), pParentWnd, 1); ////////编辑控件/////////// // if(!m_wndEdit.Create(WS_VSCROLL|WS_CHILD|WS_VISIBLE|ES_AUTOVSCROLL|ES_MULTILINE|ES_WANTRETURN,CRect(0,0,0,0),&m_wndMyBar2,101)) // return -1; // m_wndEdit.ModifyStyleEx(0,WS_EX_CLIENTEDGE); ///////////////停靠控制/////////////////// m_wndMyBar1.SetBarStyle(m_wndMyBar1.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndMyBar2.SetBarStyle(m_wndMyBar2.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndLogBar3.SetBarStyle(m_wndLogBar3.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); m_wndMyBar1.EnableDocking(CBRS_ALIGN_ANY); m_wndMyBar2.EnableDocking(CBRS_ALIGN_ANY); m_wndLogBar3.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); DockControlBar(&m_wndMyBar1, AFX_IDW_DOCKBAR_RIGHT); RecalcLayout(); CRect rect; m_wndMyBar1.GetWindowRect(rect); rect.OffsetRect(0,1);//偏移一个位置 DockControlBar(&m_wndLogBar3, AFX_IDW_DOCKBAR_RIGHT,rect);///也停靠在底部 DockControlBar(&m_wndMyBar2, AFX_IDW_DOCKBAR_BOTTOM); /////////使浮动与停靠显示相同的头部//// #ifdef _SCB_REPLACE_MINIFRAME m_pFloatingFrameClass = RUNTIME_CLASS(CSCBMiniDockFrameWnd); #endif //_SCB_REPLACE_MINIFRAME // m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); // EnableDocking(CBRS_ALIGN_ANY); // DockControlBar(&m_wndToolBar); //::SendMessage(m_log.GetSafeHwnd(),WM_LBUTTONDOWN,0x1,0x31FFF8); //::SendMessage(m_log.GetSafeHwnd(),WM_MOUSEMOVE,0x1,0xD6003F); //::SendMessage(m_log.GetSafeHwnd(),WM_LBUTTONUP,0x0,0xD6003F); return 0; }
BOOL ANCHOR_AttemptValidCylinderPos(EERIE_CYLINDER * cyl, INTERACTIVE_OBJ * io, long flags) { float anything = ANCHOR_CheckAnythingInCylinder(cyl, io, flags); if ((flags & CFLAG_LEVITATE) && (anything == 0.f)) return TRUE; if (anything >= 0.f) // Falling Cylinder but valid pos ! { if (flags & CFLAG_RETURN_HEIGHT) cyl->origin.y += anything; return TRUE; } EERIE_CYLINDER tmp; if (!(flags & CFLAG_ANCHOR_GENERATION)) { memcpy(&tmp, cyl, sizeof(EERIE_CYLINDER)); while (anything < 0.f) { tmp.origin.y += anything; anything = ANCHOR_CheckAnythingInCylinder(&tmp, io, flags); } anything = tmp.origin.y - cyl->origin.y; } if (MOVING_CYLINDER) { if (flags & CFLAG_NPC) { float tolerate; if ((io) && (io->ioflags & IO_NPC) && (io->_npcdata->pathfind.listnb > 0) && (io->_npcdata->pathfind.listpos < io->_npcdata->pathfind.listnb)) { tolerate = -80; } else tolerate = -45; if (anything < tolerate) return FALSE; } if (io && (!(flags & CFLAG_JUST_TEST))) { if ((flags & CFLAG_PLAYER) && (anything < 0.f)) { if (player.jumpphase) { io->_npcdata->climb_count = MAX_ALLOWED_PER_SECOND; return FALSE; } float dist; dist = __max(TRUEVector_Magnitude(&vector2D), 1.f); float pente; pente = EEfabs(anything) / dist * DIV2; io->_npcdata->climb_count += pente; if (io->_npcdata->climb_count > MAX_ALLOWED_PER_SECOND) { io->_npcdata->climb_count = MAX_ALLOWED_PER_SECOND; return FALSE; } if (anything < -55) { io->_npcdata->climb_count = MAX_ALLOWED_PER_SECOND; return FALSE; } } } } else if (anything < -45) return FALSE; if ((flags & CFLAG_SPECIAL) && (anything < -40)) { if (flags & CFLAG_RETURN_HEIGHT) cyl->origin.y += anything; return FALSE; } memcpy(&tmp, cyl, sizeof(EERIE_CYLINDER)); tmp.origin.y += anything; anything = ANCHOR_CheckAnythingInCylinder(&tmp, io, flags); if (anything < 0.f) { if (flags & CFLAG_RETURN_HEIGHT) { while (anything < 0.f) { tmp.origin.y += anything; anything = ANCHOR_CheckAnythingInCylinder(&tmp, io, flags); } cyl->origin.y = tmp.origin.y; } return FALSE; } cyl->origin.y = tmp.origin.y; return TRUE; }
//加注事件 bool CTableFrameSink::OnUserAddScore(WORD wChairID, LONG lScore, bool bGiveUp) { //校验用户 ASSERT(m_wCurrentUser==wChairID); if (m_wCurrentUser!=wChairID) return false; //校验金币 ASSERT((lScore +m_lTotalScore[wChairID])<= m_lUserMaxScore[wChairID]); if ((lScore+m_lTotalScore[wChairID])>m_lUserMaxScore[wChairID]) return false; ASSERT(lScore>=0L); if ((lScore<0)) return false; //累计金币 m_lTableScore[wChairID] += lScore; m_lTotalScore[wChairID] += lScore; //平衡下注 if(m_lTableScore[wChairID] > m_lBalanceScore ) { m_lBalanceScore = m_lTableScore[wChairID]; } //梭哈判断 if(m_lTotalScore[wChairID]==m_lUserMaxScore[wChairID]) { m_cbShowHand[wChairID] = TRUE; } //用户切换 WORD wNextPlayer=INVALID_CHAIR; for (WORD i=1;i<m_wPlayerCount;i++) { //设置变量 m_wOperaCount++; wNextPlayer=(m_wCurrentUser+i)%m_wPlayerCount; //继续判断 if ((m_cbPlayStatus[wNextPlayer]==TRUE) &&(m_cbShowHand[wNextPlayer] == FALSE)) break; } ASSERT(wNextPlayer < m_wPlayerCount); //完成判断 bool bFinishTurn=false; if (m_wOperaCount>=m_wPlayerCount) { WORD i=0; for ( i=0;i<m_wPlayerCount;i++) { //过滤未平衡 和未梭哈用户 if ((m_cbPlayStatus[i]==TRUE)&&(m_lTableScore[i]<m_lBalanceScore)&&(m_cbShowHand[i]==FALSE)) break; } if (i==m_wPlayerCount) bFinishTurn=true; } //A家show190,B放弃,C还选择? if(!bFinishTurn) { WORD wPlayCount = 0,wShowCount = 0; for (BYTE i=0;i<m_wPlayerCount;i++) { if(m_cbPlayStatus[i]==TRUE) { if(m_cbShowHand[i]==TRUE) { wShowCount++; } wPlayCount++; } } if(wPlayCount-1==wShowCount && m_lTableScore[wNextPlayer]>=m_lBalanceScore) bFinishTurn=true; } //继续加注 if (!bFinishTurn) { //当前用户 m_wCurrentUser=wNextPlayer; //最小值为平衡下注 -桌面下注 和 剩余金币中取小 可能梭哈 m_lTurnLessScore = min(m_lBalanceScore - m_lTableScore[m_wCurrentUser],m_lUserMaxScore[m_wCurrentUser] - m_lTotalScore[m_wCurrentUser]); m_lTurnMaxScore = m_lUserMaxScore[m_wCurrentUser]-m_lTotalScore[m_wCurrentUser]; if(m_lTotalScore[m_wCurrentUser]==m_lCellScore) { LONG bTemp = (m_lBalanceScore==m_lCellScore*2)?(m_lCellScore*2):((m_lBalanceScore-m_lCellScore*2)*2); m_lAddLessScore = m_lCellScore+bTemp; } else m_lAddLessScore = (m_lBalanceScore==0)?(2*m_lCellScore):(__max((m_lBalanceScore-m_lTableScore[m_wCurrentUser])*2,2L*m_lCellScore)); //构造数据 CMD_S_AddScore AddScore; ZeroMemory(&AddScore,sizeof(AddScore)); AddScore.lAddScoreCount=lScore; AddScore.wAddScoreUser=wChairID; AddScore.wCurrentUser=m_wCurrentUser; AddScore.lTurnLessScore=m_lTurnLessScore; AddScore.lTurnMaxScore = m_lTurnMaxScore; AddScore.lAddLessScore = m_lAddLessScore; //发送数据 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_ADD_SCORE,&AddScore,sizeof(AddScore)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_ADD_SCORE,&AddScore,sizeof(AddScore)); return true; } //平衡次数 m_cbBalanceCount++; m_wOperaCount=0; //第1次下注平衡后就开始发给三张公牌 //第2次下注平衡后就开始发第四张公牌 //第3次下注平衡后就开始发第五张公牌 //第4次下注平衡后就结束游戏 //D家下注 WORD wDUser=m_wDUser; for(BYTE i=0;i<GAME_PLAYER;i++) { wDUser=(m_wDUser+i)%GAME_PLAYER; if(m_cbPlayStatus[wDUser]==TRUE && m_cbShowHand[wDUser]==FALSE) break; } //重值变量 m_lBalanceScore = 0L; m_lTurnLessScore = 0L; m_lTurnMaxScore = m_lUserMaxScore[wDUser]-m_lTotalScore[wDUser]; m_lAddLessScore = 2*m_lCellScore; //构造数据 CMD_S_AddScore AddScore; ZeroMemory(&AddScore,sizeof(AddScore)); AddScore.wAddScoreUser=wChairID; AddScore.wCurrentUser=INVALID_CHAIR; AddScore.lAddScoreCount=lScore; AddScore.lTurnLessScore=m_lTurnLessScore; AddScore.lTurnMaxScore = m_lTurnMaxScore; AddScore.lAddLessScore = m_lAddLessScore; //清理数据 ZeroMemory(m_lTableScore,sizeof(m_lTableScore)); m_lBalanceScore = 0L; //发送数据 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_ADD_SCORE,&AddScore,sizeof(AddScore)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_ADD_SCORE,&AddScore,sizeof(AddScore)); //结束判断 if (m_cbBalanceCount == 4) { OnEventGameEnd(INVALID_CHAIR,NULL,GER_NORMAL); return true; } //梭哈用户统计 WORD wShowHandCount=0,wPlayerCount=0; for (WORD i=0;i<m_wPlayerCount;i++) { if (m_cbShowHand[i]==TRUE) wShowHandCount++; if (m_cbPlayStatus[i]==TRUE) wPlayerCount++; } //只剩一玩家没梭或者全梭 if((wShowHandCount >= wPlayerCount -1) && m_cbBalanceCount < 4) { //构造数据 CMD_S_SendCard SendCard; ZeroMemory(&SendCard,sizeof(SendCard)); SendCard.cbPublic = m_cbBalanceCount; SendCard.wCurrentUser = INVALID_CHAIR; SendCard.cbSendCardCount = MAX_CENTERCOUNT; CopyMemory(SendCard.cbCenterCardData,m_cbCenterCardData,sizeof(BYTE)*MAX_CENTERCOUNT); //发送数据 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_SEND_CARD,&SendCard,sizeof(SendCard)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_SEND_CARD,&SendCard,sizeof(SendCard)); //结束游戏 OnEventGameEnd(INVALID_CHAIR,NULL,GER_NORMAL); return true; } //盲注玩家 for (WORD i=0;i<GAME_PLAYER;i++) { //临时变量 BYTE cbNextUser =(m_wDUser+i)%GAME_PLAYER; //获取用户 IServerUserItem * pIServerUserItem=m_pITableFrame->GetServerUserItem(cbNextUser); //无效用户 梭哈用户过滤 if (pIServerUserItem==NULL||m_cbPlayStatus[cbNextUser] == FALSE||m_cbShowHand[cbNextUser] == 1) continue; m_wCurrentUser = cbNextUser; break; } //构造数据 CMD_S_SendCard SendCard; ZeroMemory(&SendCard,sizeof(SendCard)); SendCard.cbPublic = 0; SendCard.wCurrentUser = m_wCurrentUser; SendCard.cbSendCardCount = 3 +(m_cbBalanceCount-1); CopyMemory(SendCard.cbCenterCardData,m_cbCenterCardData,sizeof(BYTE)*(SendCard.cbSendCardCount)); //发送数据 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_SEND_CARD,&SendCard,sizeof(SendCard)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_SEND_CARD,&SendCard,sizeof(SendCard)); return true; }
/*! * This function is used to determine if a control needs to be painted when * it is moved or resized by the layout manager. * * @param layout Reference to a @c LAYOUTINFO structure for the control * @param rectOld Reference to a @c RECT structure that holds the control * position and size before the layout update * @param rectNew Reference to a @c RECT structure that holds the control * position and size after the layout update * * @return The return value is @c TRUE if the control should be freshly * painted after a layout update, @c FALSE if not necessary. * * @remarks The default implementation tries to identify windows that * need refresh by their class name and window style. * @n Override this function if you need a different behavior or if * you have custom controls that fail to be identified. * * @sa LikesClipping InitResizeProperties */ BOOL CResizableLayout::NeedsRefresh(const LAYOUTINFO& layout, const CRect& rectOld, const CRect& rectNew) const { if (layout.bMsgSupport) { REFRESHPROPERTY refresh; refresh.rcOld = rectOld; refresh.rcNew = rectNew; if (Send_NeedsRefresh(layout.hWnd, &refresh)) return refresh.bNeedsRefresh; } int nDiffWidth = (rectNew.Width() - rectOld.Width()); int nDiffHeight = (rectNew.Height() - rectOld.Height()); // is the same size? if (nDiffWidth == 0 && nDiffHeight == 0) return FALSE; // optimistic, no need to refresh BOOL bRefresh = FALSE; // window classes that need refresh when resized if (0 == lstrcmp(layout.sWndClass, WC_STATIC)) { DWORD style = ::GetWindowLong(layout.hWnd, GWL_STYLE); switch (style & SS_TYPEMASK) { case SS_LEFT: case SS_CENTER: case SS_RIGHT: // word-wrapped text bRefresh = bRefresh || (nDiffWidth != 0); // vertically centered text if (style & SS_CENTERIMAGE) bRefresh = bRefresh || (nDiffHeight != 0); break; case SS_LEFTNOWORDWRAP: // text with ellipsis if (style & SS_ELLIPSISMASK) bRefresh = bRefresh || (nDiffWidth != 0); // vertically centered text if (style & SS_CENTERIMAGE) bRefresh = bRefresh || (nDiffHeight != 0); break; case SS_ENHMETAFILE: case SS_BITMAP: case SS_ICON: // images case SS_BLACKFRAME: case SS_GRAYFRAME: case SS_WHITEFRAME: case SS_ETCHEDFRAME: // and frames bRefresh = TRUE; break; } return bRefresh; } // window classes that don't redraw client area correctly // when the hor scroll pos changes due to a resizing BOOL bHScroll = FALSE; if (0 == lstrcmp(layout.sWndClass, WC_LISTBOX)) bHScroll = TRUE; // fix for horizontally scrollable windows, if wider if (bHScroll && (nDiffWidth > 0)) { // get max scroll position SCROLLINFO info; info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; if (::GetScrollInfo(layout.hWnd, SB_HORZ, &info)) { // subtract the page size info.nMax -= __max(info.nPage - 1, 0); } // resizing will cause the text to scroll on the right // because the scrollbar is going beyond the right limit if ((info.nMax > 0) && (info.nPos + nDiffWidth > info.nMax)) { // needs repainting, due to horiz scrolling bRefresh = TRUE; } } return bRefresh; }
//-------------------------------------------------------------------------------------- // Returns a ranking number that describes how closely this device // combo matches the optimal combo based on the match options and the optimal device settings //-------------------------------------------------------------------------------------- float DXUTRankD3D9DeviceCombo( CD3D9EnumDeviceSettingsCombo* pDeviceSettingsCombo, DXUTD3D9DeviceSettings* pOptimalDeviceSettings, D3DDISPLAYMODE* pAdapterDesktopDisplayMode, int &bestModeIndex, int &bestMSAAIndex ) { float fCurRanking = 0.0f; // Arbitrary weights. Gives preference to the ordinal, device type, and windowed const float fAdapterOrdinalWeight = 1000.0f; const float fDeviceTypeWeight = 100.0f; const float fWindowWeight = 10.0f; const float fAdapterFormatWeight = 1.0f; const float fVertexProcessingWeight = 1.0f; const float fResolutionWeight = 1.0f; const float fBackBufferFormatWeight = 1.0f; const float fMultiSampleWeight = 1.0f; const float fDepthStencilWeight = 1.0f; const float fRefreshRateWeight = 1.0f; const float fPresentIntervalWeight = 1.0f; //--------------------- // Adapter ordinal //--------------------- if( pDeviceSettingsCombo->AdapterOrdinal == pOptimalDeviceSettings->AdapterOrdinal ) fCurRanking += fAdapterOrdinalWeight; //--------------------- // Device type //--------------------- if( pDeviceSettingsCombo->DeviceType == pOptimalDeviceSettings->DeviceType ) fCurRanking += fDeviceTypeWeight; // Slightly prefer HAL if( pDeviceSettingsCombo->DeviceType == D3DDEVTYPE_HAL ) fCurRanking += 0.1f; //--------------------- // Windowed //--------------------- if( pDeviceSettingsCombo->Windowed == pOptimalDeviceSettings->pp.Windowed ) fCurRanking += fWindowWeight; //--------------------- // Adapter format //--------------------- if( pDeviceSettingsCombo->AdapterFormat == pOptimalDeviceSettings->AdapterFormat ) { fCurRanking += fAdapterFormatWeight; } else { int nBitDepthDelta = abs( ( long )DXUTGetD3D9ColorChannelBits( pDeviceSettingsCombo->AdapterFormat ) - ( long )DXUTGetD3D9ColorChannelBits( pOptimalDeviceSettings->AdapterFormat ) ); float fScale = __max( 0.9f - ( float )nBitDepthDelta * 0.2f, 0.0f ); fCurRanking += fScale * fAdapterFormatWeight; } if( !pDeviceSettingsCombo->Windowed ) { // Slightly prefer when it matches the desktop format or is D3DFMT_X8R8G8B8 bool bAdapterOptimalMatch; if( DXUTGetD3D9ColorChannelBits( pAdapterDesktopDisplayMode->Format ) >= 8 ) bAdapterOptimalMatch = ( pDeviceSettingsCombo->AdapterFormat == pAdapterDesktopDisplayMode->Format ); else bAdapterOptimalMatch = ( pDeviceSettingsCombo->AdapterFormat == D3DFMT_X8R8G8B8 ); if( bAdapterOptimalMatch ) fCurRanking += 0.1f; } //--------------------- // Vertex processing //--------------------- if( ( pOptimalDeviceSettings->BehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING ) != 0 || ( pOptimalDeviceSettings->BehaviorFlags & D3DCREATE_MIXED_VERTEXPROCESSING ) != 0 ) { if( ( pDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) != 0 ) fCurRanking += fVertexProcessingWeight; } // Slightly prefer HW T&L if( ( pDeviceSettingsCombo->pDeviceInfo->Caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) != 0 ) fCurRanking += 0.1f; //--------------------- // Resolution //--------------------- bool bResolutionFound = false; unsigned int best = 0xffffffff; bestModeIndex=0; for( int idm = 0; idm < pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetSize(); idm++ ) { D3DDISPLAYMODE displayMode = pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( idm ); if( displayMode.Format != pDeviceSettingsCombo->AdapterFormat ) continue; if( displayMode.Width == pOptimalDeviceSettings->pp.BackBufferWidth && displayMode.Height == pOptimalDeviceSettings->pp.BackBufferHeight ) bResolutionFound = true; unsigned int current = (UINT) abs ((int)displayMode.Width - (int)pOptimalDeviceSettings->pp.BackBufferWidth) + (UINT) abs ((int)displayMode.Height - (int)pOptimalDeviceSettings->pp.BackBufferHeight ); if (current < best) { best = current; bestModeIndex= idm; } } if( bResolutionFound ) fCurRanking += fResolutionWeight; //--------------------- // Back buffer format //--------------------- if( pDeviceSettingsCombo->BackBufferFormat == pOptimalDeviceSettings->pp.BackBufferFormat ) { fCurRanking += fBackBufferFormatWeight; } else { int nBitDepthDelta = abs( ( long )DXUTGetD3D9ColorChannelBits( pDeviceSettingsCombo->BackBufferFormat ) - ( long )DXUTGetD3D9ColorChannelBits( pOptimalDeviceSettings->pp.BackBufferFormat ) ); float fScale = __max( 0.9f - ( float )nBitDepthDelta * 0.2f, 0.0f ); fCurRanking += fScale * fBackBufferFormatWeight; } // Check if this back buffer format is the same as // the adapter format since this is preferred. bool bAdapterMatchesBB = ( pDeviceSettingsCombo->BackBufferFormat == pDeviceSettingsCombo->AdapterFormat ); if( bAdapterMatchesBB ) fCurRanking += 0.1f; //--------------------- // Back buffer count //--------------------- // No caps for the back buffer count //--------------------- // Multisample //--------------------- bool bMultiSampleFound = false; for( int i = 0; i < pDeviceSettingsCombo->multiSampleTypeList.GetSize(); i++ ) { D3DMULTISAMPLE_TYPE msType = pDeviceSettingsCombo->multiSampleTypeList.GetAt( i ); DWORD msQuality = pDeviceSettingsCombo->multiSampleQualityList.GetAt( i ); if( msType == pOptimalDeviceSettings->pp.MultiSampleType && msQuality > pOptimalDeviceSettings->pp.MultiSampleQuality ) { bMultiSampleFound = true; bestMSAAIndex = i; break; } } if( bMultiSampleFound ) fCurRanking += fMultiSampleWeight; //--------------------- // Swap effect //--------------------- // No caps for swap effects //--------------------- // Depth stencil //--------------------- if( pDeviceSettingsCombo->depthStencilFormatList.Contains( pOptimalDeviceSettings->pp.AutoDepthStencilFormat ) ) fCurRanking += fDepthStencilWeight; //--------------------- // Present flags //--------------------- // No caps for the present flags //--------------------- // Refresh rate //--------------------- bool bRefreshFound = false; for( int idm = 0; idm < pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetSize(); idm++ ) { D3DDISPLAYMODE displayMode = pDeviceSettingsCombo->pAdapterInfo->displayModeList.GetAt( idm ); if( displayMode.Format != pDeviceSettingsCombo->AdapterFormat ) continue; if( displayMode.RefreshRate == pOptimalDeviceSettings->pp.FullScreen_RefreshRateInHz ) bRefreshFound = true; } if( bRefreshFound ) fCurRanking += fRefreshRateWeight; //--------------------- // Present interval //--------------------- // If keep present interval then check that the present interval is supported by this combo if( pDeviceSettingsCombo->presentIntervalList.Contains( pOptimalDeviceSettings->pp.PresentationInterval ) ) fCurRanking += fPresentIntervalWeight; return fCurRanking; }
// 描画 void CMusicalScoreTrackScaleView::OnDraw (CDC* pDC) { CMusicalScoreFrame* pMusicalScoreFrame = (CMusicalScoreFrame*)GetParent (); CSekaijuApp* pSekaijuApp = (CSekaijuApp*)AfxGetApp (); CSekaijuDoc* pSekaijuDoc = GetDocument(); ASSERT_VALID (pSekaijuDoc); MIDIData* pMIDIData = pSekaijuDoc->m_pMIDIData; CRect rcClient; GetClientRect (&rcClient); CFont* pOldFont = NULL; pDC->SetBkMode (TRANSPARENT); long lTrackZoom = pMusicalScoreFrame->GetTrackZoom (); long lVisibleTopTrack = pMusicalScoreFrame->GetVisibleTopTrack (); long lVisibleBottomTrack = pMusicalScoreFrame->GetVisibleBottomTrack (); long rx = 4; long ry = 4; BOOL bTrackZeroOrigin = pSekaijuApp->m_theGeneralOption.m_bTrackZeroOrigin; long i = 0; MIDITrack* pTempTrack = NULL; // ボタン部描画 i = 0; long lColorBtnFace = ::GetSysColor (COLOR_BTNFACE); long lColorBtnShadow = ::GetSysColor (COLOR_BTNSHADOW); long lColorBtnHighlight = ::GetSysColor (COLOR_BTNHIGHLIGHT); long lColorBtnText = ::GetSysColor (COLOR_BTNTEXT); long lColorBlack = RGB (0, 0, 0); long lColorWhite = RGB (255, 255, 255); pOldFont = pDC->SelectObject (&(pMusicalScoreFrame->m_theFont)); forEachTrack (pMIDIData, pTempTrack) { if (pMusicalScoreFrame->IsTrackVisible (i)) { if (lVisibleTopTrack <= i && i <= lVisibleBottomTrack) { MusicalScoreTrackInfo* pTrackInfo = pMusicalScoreFrame->GetTrackInfo (i); TCHAR szBuf[256]; memset (szBuf, 0, sizeof (szBuf)); _sntprintf (szBuf, 255, _T("%d"), i + (bTrackZeroOrigin ? 0 : 1)); BOOL bSelectTrack = TRUE; long lCount = 0; MIDIEvent* pTempEvent = NULL; forEachEvent (pTempTrack, pTempEvent) { if (MIDIEvent_IsNoteOn (pTempEvent)) { if (!pSekaijuDoc->IsEventSelected (pTempEvent)) { bSelectTrack = FALSE; } lCount++; } } if (GetCapture () == this) { long lMinTrack = __min (m_lDownTrack, m_lCurTrack); long lMaxTrack = __max (m_lDownTrack, m_lCurTrack); if (lMinTrack <= i && i <= lMaxTrack) { bSelectTrack = TRUE; } } CRect theRect (0, pTrackInfo->m_lTop * lTrackZoom, 32, (pTrackInfo->m_lTop + pTrackInfo->m_lHeight) * lTrackZoom); if (bSelectTrack && lCount > 0) { pDC->FillSolidRect (&theRect, lColorBlack); pDC->Draw3dRect (&theRect, lColorBlack, lColorBtnShadow); pDC->SetTextColor (lColorWhite); pDC->DrawText (szBuf, -1, &theRect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); } else { pDC->FillSolidRect (&theRect, lColorBtnFace); pDC->Draw3dRect (&theRect, lColorBtnHighlight, lColorBtnShadow); pDC->SetTextColor (lColorBtnText); pDC->DrawText (szBuf, -1, &theRect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); } } } i++; }
BOOL CMesh::loadFromSMF(CString sFileName) // ----- format: smf,obj,dat ----- //vertex: // v x y z, //face(triangle): // f v1 v2 v3 (the vertex index is 1-based) { //open the file FILE *f = NULL; if ((f = fopen(LPCTSTR(sFileName),"rb")) == NULL) return FALSE; char ch = 0; _VECTORLIST VertexList;//临时存储所有点的链表 _UINTLIST FaceList;//临时存储所有面包含的点的信息 Vector3D vector; Vector3D vMin; Vector3D vMax; bool bFirst=true; UINT l[3]; short j; ch=fgetc(f); while(ch>0)//将点和面的信息临时存在VertexList和FaceList中 { switch(ch) { case 'v': //vertex ch=fgetc(f); if((ch!=' ')&&(ch!='\t')) break; fscanf(f, "%lf%lf%lf",&vector.x,&vector.y,&vector.z); VertexList.push_back(Vector3D(vector)); //计算所有点的包围盒 if(bFirst) { bFirst=false; vMin=vMax=vector; continue; } if(vector.x<vMin.x) vMin.x=vector.x; else if(vector.x>vMax.x) vMax.x=vector.x; if(vector.y<vMin.y) vMin.y=vector.y; else if(vector.y>vMax.y) vMax.y=vector.y; if(vector.z<vMin.z) vMin.z=vector.z; else if(vector.z>vMax.z) vMax.z=vector.z; break; case 'f': //face ch=fgetc(f); if((ch!=' ')&&(ch!='\t')) break; fscanf(f, "%ld%ld%ld\n",&l[0],&l[1],&l[2]); for(j=0;j<3;j++) FaceList.push_back(l[j]-1); break; } ch=fgetc(f); } fclose(f); //根据包围盒将物体中心移至原点,同时进行归一化 vector=vMax-vMin; double d=__max(vector.x,vector.y); d=0.5*__max(d,vector.z); vector=0.5*(vMax+vMin);//偏移量 m_nVertex=VertexList.size(); m_nFace=FaceList.size()/3; m_nEdge=3*m_nFace; //read vertices and faces m_pVertex = new CVertex[m_nVertex]; if (m_pVertex==NULL) {clear(); return FALSE;}//out of memory m_pFace = new CFace[m_nFace]; if (m_pFace == NULL) {clear(); return FALSE;}//out of memory UINT i; _VECTORLIST::iterator iVertex = VertexList.begin(); _UINTLIST::iterator iFace = FaceList.begin(); for(i=0;i<m_nVertex;i++) m_pVertex[i].m_vPosition=(*(iVertex++)-vector)/d; for(i=0;i<m_nFace;i++) { m_pFace[i].Create(3); for(j=0;j<3;j++) m_pFace[i].m_piVertex[j]=*iFace++; } VertexList.clear(); FaceList.clear(); return construct(); }
void RGBtoHSBService (double dRed, double dGreen, double dBlue, double &rdHue, double &rdSat, double &rdBright) { // 1. Helligkeit berechnen double dYR = HelligkeitRot(dRed); double dYG = HelligkeitGruen(dGreen); double dYB = HelligkeitBlau(dBlue); double dY = dYR + dYG + dYB; // Gesamtluminanz rdBright = Wahrnehmung(dY); // 2. Sättigung berechnen double dYRGrau = BEZUGSWERT_ROT*dY; // anteilige Helligkeiten des zugehörigen Grauwertes double dYGGrau = BEZUGSWERT_GRUEN*dY; double dYBGrau = BEZUGSWERT_BLAU*dY; HIGHLOW rgStatus = HIGHLOW_UNKNOWN; TARGETCOLOR rgTarget = TARGETCOLOR_UNKNOWN; // 2.1. testen, ob eine der Farbanteile bereits gesättigt ist double dYRSatt = dYR; double dYGSatt = dYG; double dYBSatt = dYB; int fSaturatedRot = IsSaturated (dYR, BEZUGSWERT_ROT); int fSaturatedGruen = IsSaturated (dYG, BEZUGSWERT_GRUEN); int fSaturatedBlau = IsSaturated (dYB, BEZUGSWERT_BLAU); int fSaturatedSum = fSaturatedRot & fSaturatedGruen; fSaturatedSum &= fSaturatedBlau; if (fSaturatedSum) { // weiß oder schwarz rdSat = 0.0; // Farbe ist vollständig entsättigt rdHue = 0.0; // per Definition return; } if (fSaturatedRot) { rgStatus = (0.0 == dYR) ? HIGHLOW_LOW : HIGHLOW_HIGH; rgTarget = TARGETCOLOR_RED; rdSat = 1.0; // volle Sättigung } else if (fSaturatedGruen) { rgStatus = (0.0 == dYG) ? HIGHLOW_LOW : HIGHLOW_HIGH; rgTarget = TARGETCOLOR_GREEN; rdSat = 1.0; // volle Sättigung } else if (fSaturatedBlau) { rgStatus = (0.0 == dYB) ? HIGHLOW_LOW : HIGHLOW_HIGH; rgTarget = TARGETCOLOR_BLUE; rdSat = 1.0; // volle Sättigung } else { // gesättigte Farbe bestimmen HIGHLOW rgRStatus = HIGHLOW_UNKNOWN; HIGHLOW rgGStatus = HIGHLOW_UNKNOWN; HIGHLOW rgBStatus = HIGHLOW_UNKNOWN; double dKR = EvalSatKoeff (dYRGrau, dYR, BEZUGSWERT_ROT, rgRStatus); double dKG = EvalSatKoeff (dYGGrau, dYG, BEZUGSWERT_GRUEN, rgGStatus); double dKB = EvalSatKoeff (dYBGrau, dYB, BEZUGSWERT_BLAU, rgBStatus); // der Farbanteil mit dem maximalen (inversen) Koeffizienten // ist die entscheidende double dKMax = __max(fabs(dKR), __max(fabs(dKG), fabs(dKB))); if (0.0 == dKMax) { rdSat = 0.0; // Farbe ist vollständig entsättigt rdHue = 0.0; // per Definition return; } else { if (dKMax == fabs(dKR)) { rgStatus = rgRStatus; rgTarget = TARGETCOLOR_RED; } else if (dKMax == fabs(dKG)) { rgStatus = rgGStatus; rgTarget = TARGETCOLOR_GREEN; } else if (dKMax == fabs(dKB)) { rgStatus = rgBStatus; rgTarget = TARGETCOLOR_BLUE; } // gesättigte Farbanteile berechnen dYRSatt = CorrectColor (dYRGrau, dYR, dKMax); dYGSatt = CorrectColor (dYGGrau, dYG, dKMax); dYBSatt = CorrectColor (dYBGrau, dYB, dKMax); if (dYRSatt != dYRGrau) rdSat = (dYR - dYRGrau)/(dYRSatt - dYRGrau); else if (dYGSatt != dYGGrau) rdSat = (dYG - dYGGrau)/(dYGSatt - dYGGrau); else if (dYBSatt != dYBGrau) rdSat = (dYB - dYBGrau)/(dYBSatt - dYBGrau); else ASSERT(false); } } ASSERT(rgTarget != TARGETCOLOR_UNKNOWN); ASSERT(rgStatus != HIGHLOW_UNKNOWN); // 3. Farbwert bestimmen double dRSatt = Farbanteil (dYRSatt, BEZUGSWERT_ROT); double dGSatt = Farbanteil (dYGSatt, BEZUGSWERT_GRUEN); double dBSatt = Farbanteil (dYBSatt, BEZUGSWERT_BLAU); if (HIGHLOW_LOW == rgStatus) { switch (rgTarget) { case TARGETCOLOR_RED: rdHue = GetHue (dGSatt, dBSatt) + 3.0; break; case TARGETCOLOR_GREEN: rdHue = GetHue (dBSatt, dRSatt) + 5.0; break; case TARGETCOLOR_BLUE: rdHue = GetHue (dRSatt, dGSatt) + 1.0; break; } } else { switch (rgTarget) { case TARGETCOLOR_RED: rdHue = GetHue (1.0-dGSatt, 1.0-dBSatt); if (rdHue < 0.0) rdHue += 6.0; break; case TARGETCOLOR_GREEN: rdHue = GetHue (1.0-dBSatt, 1.0-dRSatt) + 2.0; break; case TARGETCOLOR_BLUE: rdHue = GetHue (1.0-dRSatt, 1.0-dGSatt) + 4.0; break; } } rdHue *= 60.0; while (rdHue >= 360.0) rdHue -= 360.0; }
void CameraController::Update() { if ( m_ZoomDirection == ZOOM_DIRECTION_NONE ) { return; } float targetY = 0; float targetViewY = 0; switch ( m_ZoomStatus ) { case ZOOM_STATUS_NEAREST: targetY = NEAREST_Y; targetViewY = NEAREST_VIEW_Y; break; case ZOOM_STATUS_DEGREE_1: targetY = DEGREE_1_Y; targetViewY = DEGREE_1_VIEW_Y; break; case ZOOM_STATUS_DEGREE_2: targetY = DEGREE_2_Y; targetViewY = DEGREE_2_VIEW_Y; break; case ZOOM_STATUS_DEGREE_3: targetY = DEGREE_3_Y; targetViewY = DEGREE_3_VIEW_Y; break; case ZOOM_STATUS_FARTHEST: default: targetY = FARTHEST_Y; targetViewY = FARTHEST_VIEW_Y; break; } float time = static_cast<float>( Timer::GetInstance()->GetElapsedTime() ) / 1000; float delta = time * 10.0f; D3DXVECTOR3 view = m_LookAtPoint - m_EyePoint; D3DXVec3Normalize( &view, &view ); float dotView = D3DXVec3Dot( &view, &( -m_UpVector ) ); // Log( "%-8f도!!! %-8f \n", dotView, targetViewY ); // Log( "목표 = %f, 현위치 = %f \n", targetY, m_EyePoint.y ); // 카메라 업 if ( m_ZoomDirection == ZOOM_DIRECTION_BACK ) { if ( dotView < targetViewY ) { RotateUp( delta * dotView / ( m_EyePoint.y / 10 ) ); } MoveElevate( delta * 10 ); MoveForward( -delta * 10, true ); if ( targetY < m_EyePoint.y ) { m_ZoomDirection = ZOOM_DIRECTION_NONE; return; } } // 카메라 다운 else if ( m_ZoomDirection == ZOOM_DIRECTION_FOWARD ) { if ( dotView > targetViewY ) { RotateUp( -delta * dotView / ( m_EyePoint.y / 10 ) ); } MoveElevate( -delta * 10 ); MoveForward( delta * 10, true ); if ( targetY > m_EyePoint.y ) { m_ZoomDirection = ZOOM_DIRECTION_NONE; return; } } if ( m_ZoomPointX > 0 ) { m_ZoomPointX = __min( m_ZoomPointX, 50 ); m_ZoomPointX -= delta; MoveSide( delta ); } else if ( m_ZoomPointX < 0 ) { m_ZoomPointX = __max( m_ZoomPointX, -50 ); m_ZoomPointX += delta; MoveSide( -delta ); } if ( m_ZoomPointY > 0 ) { m_ZoomPointY = __min( m_ZoomPointY, 50 ); m_ZoomPointY -= delta; MoveForward( -delta ); } else if ( m_ZoomPointY < 0 ) { m_ZoomPointY = __max( m_ZoomPointY, -50 ); m_ZoomPointY += delta; MoveForward( delta ); } }
void stretch_tabstops(sptr_t edit, int block_start_linenum, int block_nof_lines, int max_tabs) { int l, t; et_line* lines = (et_line*)_alloca(sizeof (et_line) * block_nof_lines); memset(lines,0,sizeof (et_line) * block_nof_lines); int new_buffer_size = sizeof (et_tabstop) * __max(1,block_nof_lines * max_tabs); if (new_buffer_size > grid_buffer_size) { et_tabstop* new_buffer = (et_tabstop*)realloc(grid_buffer,new_buffer_size); if (new_buffer == NULL) { return; } grid_buffer = new_buffer; grid_buffer_size = new_buffer_size; } memset(grid_buffer,0,new_buffer_size); et_tabstop** grid = (et_tabstop**)_alloca(sizeof (et_tabstop*) * block_nof_lines); for (l = 0; l < block_nof_lines; l++) { grid[l] = grid_buffer + (l * max_tabs); } // get width of text in cells for (l = 0; l < block_nof_lines; l++) // for each line { int text_width_in_tab = 0; int current_line_num = block_start_linenum + l; int current_tab_num = 0; bool cell_empty = true; int current_pos = call_edit(edit,SCI_POSITIONFROMLINE,current_line_num); int cell_start = current_pos; unsigned char current_char = (unsigned char)call_edit(edit,SCI_GETCHARAT,current_pos); bool current_char_ends_line = is_line_end(edit,current_pos); // maybe change this to search forwards for tabs/newlines while (current_char != '\0') { if (current_char_ends_line) { grid[l][current_tab_num].ends_in_tab = false; text_width_in_tab = 0; break; } else if (current_char == '\t') { if (!cell_empty) { text_width_in_tab = get_text_width(edit,cell_start,current_pos); } grid[l][current_tab_num].ends_in_tab = true; grid[l][current_tab_num].text_width_pix = calc_tab_width(text_width_in_tab); current_tab_num++; lines[l].num_tabs++; text_width_in_tab = 0; cell_empty = true; } else { if (cell_empty) { cell_start = current_pos; cell_empty = false; } } current_pos = call_edit(edit,SCI_POSITIONAFTER,current_pos); current_char = (unsigned char)call_edit(edit,SCI_GETCHARAT,current_pos); current_char_ends_line = is_line_end(edit,current_pos); } } // find columns blocks and stretch to fit the widest cell for (t = 0; t < max_tabs; t++) // for each column { bool starting_new_block = true; int first_line_in_block = 0; int max_width = 0; for (l = 0; l < block_nof_lines; l++) // for each line { if (starting_new_block) { starting_new_block = false; first_line_in_block = l; max_width = 0; } if (grid[l][t].ends_in_tab) { grid[l][t].widest_width_pix = &(grid[first_line_in_block][t].text_width_pix); // point widestWidthPix at first if (grid[l][t].text_width_pix > max_width) { max_width = grid[l][t].text_width_pix; grid[first_line_in_block][t].text_width_pix = max_width; } } else // end column block { starting_new_block = true; } } } std::vector<int> tab_array; // set tabstops for (l = 0; l < block_nof_lines; l++) // for each line { int current_line_num = block_start_linenum + l; int acc_tabstop = 0; tab_array.resize(lines[l].num_tabs + 1); tab_array[lines[l].num_tabs] = 0; for (t = 0; t < lines[l].num_tabs; t++) { if (grid[l][t].widest_width_pix != NULL) { acc_tabstop += *(grid[l][t].widest_width_pix); tab_array[t] = acc_tabstop; } else { tab_array[t] = 0; } } call_edit(edit,SCI_SETTABSTOPS,current_line_num,(LONG_PTR)&(tab_array.at(0))); } }
//游戏结束 bool __cdecl CTableFrameSink::OnEventGameEnd( WORD wChairID, IServerUserItem * pIServerUserItem, BYTE cbReason ) { switch ( cbReason ) { case GER_DISMISS: //游戏解散 { //效验参数 ASSERT( pIServerUserItem != NULL ); ASSERT( wChairID < m_wPlayerCount ); //构造数据 CMD_S_GameEnd GameEnd; memset( &GameEnd, 0, sizeof( GameEnd ) ); //剩余扑克 BYTE bCardPos = 0; for ( WORD i = 0; i < m_wPlayerCount; i++ ) { GameEnd.bCardCount[ i ] = m_bCardCount[ i ]; CopyMemory( &GameEnd.bCardData[ bCardPos ], m_bHandCardData[ i ], m_bCardCount[ i ] * sizeof( BYTE ) ); bCardPos += m_bCardCount[ i ]; } //发送信息 m_pITableFrame->SendTableData( INVALID_CHAIR, SUB_S_GAME_END, &GameEnd, sizeof( GameEnd ) ); m_pITableFrame->SendLookonData( INVALID_CHAIR, SUB_S_GAME_END, &GameEnd, sizeof( GameEnd ) ); //结束游戏 m_pITableFrame->ConcludeGame(); return true; } case GER_NORMAL: //常规结束 { //定义变量 CMD_S_GameEnd GameEnd; ZeroMemory( &GameEnd, sizeof( GameEnd ) ); //剩余扑克 BYTE bCardPos = 0; for ( WORD i = 0; i < m_wPlayerCount; i++ ) { GameEnd.bCardCount[ i ] = m_bCardCount[ i ]; CopyMemory( &GameEnd.bCardData[ bCardPos ], m_bHandCardData[ i ], m_bCardCount[ i ] * sizeof( BYTE ) ); bCardPos += m_bCardCount[ i ]; } //变量定义 LONG lCellScore = m_pGameServiceOption->lCellScore; bool bLandWin = ( m_bCardCount[ m_wBankerUser ] == 0 ) ? true : false; //春天判断 if ( wChairID == m_wBankerUser ) { WORD wUser1 = ( m_wBankerUser + 1 ) % GAME_PLAYER; WORD wUser2 = ( m_wBankerUser + 2 ) % GAME_PLAYER; if ( ( m_bOutCardCount[ wUser1 ] == 0 ) && ( m_bOutCardCount[ wUser2 ] == 0 ) ) m_wBombTime *= 2; } else { if ( m_bOutCardCount[ m_wBankerUser ] == 1 ) m_wBombTime *= 2; } //炸弹限制 m_wBombTime = __min( m_wBombTime, 16 ); //游戏积分 LONG lScore=0; LONG lRevenue=0; enScoreKind ScoreKind; //统计积分 for ( WORD i = 0; i < m_wPlayerCount; i++ ) { lScore=0; lRevenue=0; //统计积分 if ( i == m_wBankerUser ) { lScore = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? 2 : -2 ); GameEnd.lGameScore[ i ] = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? 2 : -2 ); } else { lScore = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? -1 : 1 ); GameEnd.lGameScore[ i ] = m_wBombTime * m_bLandScore * lCellScore * ( ( bLandWin == true ) ? -1 : 1 ); } //胜利类型 ScoreKind=(GameEnd.lGameScore[i]>0L)?enScoreKind_Win:enScoreKind_Lost; //计算税收 if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD) { if (GameEnd.lGameScore[i]>=100L) { //计算税收 GameEnd.lGameTax+= (GameEnd.lGameScore[i]*m_pGameServiceOption->wRevenue/1000L); lRevenue = (GameEnd.lGameScore[i]*m_pGameServiceOption->wRevenue/1000L); //积分调整 lScore=lScore-lRevenue; GameEnd.lGameScore[i]=GameEnd.lGameScore[i]-lRevenue; } } //修改分数 m_pITableFrame->WriteUserScore(i,lScore,lRevenue,ScoreKind); //历史积分 m_HistoryScore.OnEventUserScore(i,GameEnd.lGameScore[i]); } //发送信息 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); //切换用户 m_wFirstUser=wChairID; //结束游戏 m_pITableFrame->ConcludeGame(); return true; } case GER_USER_LEFT: //用户强退 { //效验参数 ASSERT(pIServerUserItem!=NULL); ASSERT(wChairID<m_wPlayerCount); //构造数据 CMD_S_GameEnd GameEnd; ZeroMemory(&GameEnd,sizeof(GameEnd)); //剩余扑克 BYTE bCardPos=0; for (WORD i=0;i<m_wPlayerCount;i++) { GameEnd.bCardCount[i]=m_bCardCount[i]; CopyMemory(&GameEnd.bCardData[bCardPos],m_bHandCardData[i],m_bCardCount[i]*sizeof(BYTE)); bCardPos+=m_bCardCount[i]; } //炸弹限制 m_wBombTime=__min(m_wBombTime,16); m_bLandScore=__max(m_bLandScore,1); //修改积分 for (WORD i=0;i<m_wPlayerCount;i++) { //游戏积分 LONG lScore=0; LONG lRevenue=0; enScoreKind ScoreKind=enScoreKind_Draw; //构造变量 if (i==wChairID) { ScoreKind=enScoreKind_Flee; lScore =-m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*2; GameEnd.lGameScore[i]=-m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*2; } else if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD) { //统计积分 //ScoreKind=enScoreKind_Win; //lScore=(m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*4)/2; //GameEnd.lGameScore[i]=(m_wBombTime*m_bLandScore*m_pGameServiceOption->lCellScore*4)/2; ////计算税收 //if (lScore>=100L) //{ // //计算税收 // GameEnd.lGameTax+=GameEnd.lGameScore[i]*m_pGameServiceOption->cbRevenue/100L; // lRevenue = GameEnd.lGameScore[i]*m_pGameServiceOption->cbRevenue/100L; // //积分调整 // lScore=lScore-lRevenue ; // GameEnd.lGameScore[i]=GameEnd.lGameScore[i]-lRevenue ; //} } //写入积分 m_pITableFrame->WriteUserScore(i,lScore,lRevenue,ScoreKind); //历史积分 m_HistoryScore.OnEventUserScore(i,GameEnd.lGameScore[i]); } //发送信息 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); //结束游戏 m_pITableFrame->ConcludeGame(); return true; } } ASSERT(FALSE); return false; }
int main() { TCAS_pFile pFile; TCAS_pHeader pHeader; TCAS_pRawChunk pRawChunk; pFile = (TCAS_pFile)malloc(sizeof(TCAS_File)); memset(pFile, 0, sizeof(TCAS_File)); pFile->minTime = TCAS_INIT_MIN_TIME; pHeader = (TCAS_pHeader)malloc(sizeof(TCAS_Header)); pRawChunk = (TCAS_pRawChunk)malloc(4 * sizeof(TCAS_RawChunk)); pRawChunk[0].startTime = 0; pRawChunk[0].endTime = 100; pRawChunk[0].frameType = 0; pRawChunk[0].layer = 5; pRawChunk[0].posX = 100; pRawChunk[0].posY = 100; pRawChunk[0].r = (tcas_byte)1; pRawChunk[0].g = (tcas_byte)2; pRawChunk[0].b = (tcas_byte)3; pRawChunk[0].a = (tcas_byte)4; pFile->minTime = __min(pFile->minTime, pRawChunk[0].startTime); pFile->maxTime = __max(pFile->maxTime, pRawChunk[0].endTime); pFile->chunks ++; pRawChunk[1].startTime = 200; pRawChunk[1].endTime = 300; pRawChunk[1].frameType = 0; pRawChunk[1].layer = 1; pRawChunk[1].posX = 200; pRawChunk[1].posY = 100; pRawChunk[1].r = (tcas_byte)5; pRawChunk[1].g = (tcas_byte)6; pRawChunk[1].b = (tcas_byte)7; pRawChunk[1].a = (tcas_byte)8; pFile->minTime = __min(pFile->minTime, pRawChunk[1].startTime); pFile->maxTime = __max(pFile->maxTime, pRawChunk[1].endTime); pFile->chunks ++; pRawChunk[2].startTime = 400; pRawChunk[2].endTime = 500; pRawChunk[2].frameType = 0; pRawChunk[2].layer = 3; pRawChunk[2].posX = 100; pRawChunk[2].posY = 200; pRawChunk[2].r = (tcas_byte)1; pRawChunk[2].g = (tcas_byte)2; pRawChunk[2].b = (tcas_byte)3; pRawChunk[2].a = (tcas_byte)4; pFile->minTime = __min(pFile->minTime, pRawChunk[2].startTime); pFile->maxTime = __max(pFile->maxTime, pRawChunk[2].endTime); pFile->chunks ++; pRawChunk[3].startTime = 400; pRawChunk[3].endTime = 500; pRawChunk[3].frameType = 0; pRawChunk[3].layer = 3; pRawChunk[3].posX = 200; pRawChunk[3].posY = 200; pRawChunk[3].r = (tcas_byte)1; pRawChunk[3].g = (tcas_byte)2; pRawChunk[3].b = (tcas_byte)3; pRawChunk[3].a = (tcas_byte)4; pFile->minTime = __min(pFile->minTime, pRawChunk[3].startTime); pFile->maxTime = __max(pFile->maxTime, pRawChunk[3].endTime); pFile->chunks ++; libtcas_open_file(pFile, "test_raw.tcas", tcas_file_create_new); libtcas_set_file_position_indicator(pFile, tcas_fpi_header); libtcas_write_raw_chunks(pFile, pRawChunk, 4); libtcas_set_header(pHeader, TCAS_FILE_TYPE_RAW, 0, 640, 480, pFile->minTime, pFile->maxTime, pFile->chunks, 1, 1); libtcas_write_header(pFile, pHeader, tcas_false); libtcas_close_file(pFile); free(pRawChunk); free(pHeader); free(pFile); return 0; }
ALvoid aluInitPanning(ALCdevice *Device) { ALfloat SpeakerAngle[MAXCHANNELS]; ALfloat (*Matrix)[MAXCHANNELS]; Channel *Speaker2Chan; ALfloat Alpha, Theta; ALfloat *PanningLUT; ALint pos, offset; ALuint s, s2; for(s = 0;s < MAXCHANNELS;s++) { for(s2 = 0;s2 < MAXCHANNELS;s2++) Device->ChannelMatrix[s][s2] = ((s==s2) ? 1.0f : 0.0f); } Speaker2Chan = Device->Speaker2Chan; Matrix = Device->ChannelMatrix; switch(Device->FmtChans) { case DevFmtMono: Matrix[FRONT_LEFT][FRONT_CENTER] = aluSqrt(0.5); Matrix[FRONT_RIGHT][FRONT_CENTER] = aluSqrt(0.5); Matrix[SIDE_LEFT][FRONT_CENTER] = aluSqrt(0.5); Matrix[SIDE_RIGHT][FRONT_CENTER] = aluSqrt(0.5); Matrix[BACK_LEFT][FRONT_CENTER] = aluSqrt(0.5); Matrix[BACK_RIGHT][FRONT_CENTER] = aluSqrt(0.5); Matrix[BACK_CENTER][FRONT_CENTER] = 1.0f; Device->NumChan = 1; Speaker2Chan[0] = FRONT_CENTER; SpeakerAngle[0] = 0.0f * M_PI/180.0f; break; case DevFmtStereo: Matrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5); Matrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5); Matrix[SIDE_LEFT][FRONT_LEFT] = 1.0f; Matrix[SIDE_RIGHT][FRONT_RIGHT] = 1.0f; Matrix[BACK_LEFT][FRONT_LEFT] = 1.0f; Matrix[BACK_RIGHT][FRONT_RIGHT] = 1.0f; Matrix[BACK_CENTER][FRONT_LEFT] = aluSqrt(0.5); Matrix[BACK_CENTER][FRONT_RIGHT] = aluSqrt(0.5); Device->NumChan = 2; Speaker2Chan[0] = FRONT_LEFT; Speaker2Chan[1] = FRONT_RIGHT; SpeakerAngle[0] = -90.0f * M_PI/180.0f; SpeakerAngle[1] = 90.0f * M_PI/180.0f; SetSpeakerArrangement("layout_STEREO", SpeakerAngle, Speaker2Chan, Device->NumChan); break; case DevFmtQuad: Matrix[FRONT_CENTER][FRONT_LEFT] = aluSqrt(0.5); Matrix[FRONT_CENTER][FRONT_RIGHT] = aluSqrt(0.5); Matrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5); Matrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5); Matrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5); Matrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5); Matrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5); Matrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5); Device->NumChan = 4; Speaker2Chan[0] = BACK_LEFT; Speaker2Chan[1] = FRONT_LEFT; Speaker2Chan[2] = FRONT_RIGHT; Speaker2Chan[3] = BACK_RIGHT; SpeakerAngle[0] = -135.0f * M_PI/180.0f; SpeakerAngle[1] = -45.0f * M_PI/180.0f; SpeakerAngle[2] = 45.0f * M_PI/180.0f; SpeakerAngle[3] = 135.0f * M_PI/180.0f; SetSpeakerArrangement("layout_QUAD", SpeakerAngle, Speaker2Chan, Device->NumChan); break; case DevFmtX51: Matrix[SIDE_LEFT][FRONT_LEFT] = aluSqrt(0.5); Matrix[SIDE_LEFT][BACK_LEFT] = aluSqrt(0.5); Matrix[SIDE_RIGHT][FRONT_RIGHT] = aluSqrt(0.5); Matrix[SIDE_RIGHT][BACK_RIGHT] = aluSqrt(0.5); Matrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5); Matrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5); Device->NumChan = 5; Speaker2Chan[0] = BACK_LEFT; Speaker2Chan[1] = FRONT_LEFT; Speaker2Chan[2] = FRONT_CENTER; Speaker2Chan[3] = FRONT_RIGHT; Speaker2Chan[4] = BACK_RIGHT; SpeakerAngle[0] = -110.0f * M_PI/180.0f; SpeakerAngle[1] = -30.0f * M_PI/180.0f; SpeakerAngle[2] = 0.0f * M_PI/180.0f; SpeakerAngle[3] = 30.0f * M_PI/180.0f; SpeakerAngle[4] = 110.0f * M_PI/180.0f; SetSpeakerArrangement("layout_51CHN", SpeakerAngle, Speaker2Chan, Device->NumChan); break; case DevFmtX61: Matrix[BACK_LEFT][BACK_CENTER] = aluSqrt(0.5); Matrix[BACK_LEFT][SIDE_LEFT] = aluSqrt(0.5); Matrix[BACK_RIGHT][BACK_CENTER] = aluSqrt(0.5); Matrix[BACK_RIGHT][SIDE_RIGHT] = aluSqrt(0.5); Device->NumChan = 6; Speaker2Chan[0] = SIDE_LEFT; Speaker2Chan[1] = FRONT_LEFT; Speaker2Chan[2] = FRONT_CENTER; Speaker2Chan[3] = FRONT_RIGHT; Speaker2Chan[4] = SIDE_RIGHT; Speaker2Chan[5] = BACK_CENTER; SpeakerAngle[0] = -90.0f * M_PI/180.0f; SpeakerAngle[1] = -30.0f * M_PI/180.0f; SpeakerAngle[2] = 0.0f * M_PI/180.0f; SpeakerAngle[3] = 30.0f * M_PI/180.0f; SpeakerAngle[4] = 90.0f * M_PI/180.0f; SpeakerAngle[5] = 180.0f * M_PI/180.0f; SetSpeakerArrangement("layout_61CHN", SpeakerAngle, Speaker2Chan, Device->NumChan); break; case DevFmtX71: Matrix[BACK_CENTER][BACK_LEFT] = aluSqrt(0.5); Matrix[BACK_CENTER][BACK_RIGHT] = aluSqrt(0.5); Device->NumChan = 7; Speaker2Chan[0] = BACK_LEFT; Speaker2Chan[1] = SIDE_LEFT; Speaker2Chan[2] = FRONT_LEFT; Speaker2Chan[3] = FRONT_CENTER; Speaker2Chan[4] = FRONT_RIGHT; Speaker2Chan[5] = SIDE_RIGHT; Speaker2Chan[6] = BACK_RIGHT; SpeakerAngle[0] = -150.0f * M_PI/180.0f; SpeakerAngle[1] = -90.0f * M_PI/180.0f; SpeakerAngle[2] = -30.0f * M_PI/180.0f; SpeakerAngle[3] = 0.0f * M_PI/180.0f; SpeakerAngle[4] = 30.0f * M_PI/180.0f; SpeakerAngle[5] = 90.0f * M_PI/180.0f; SpeakerAngle[6] = 150.0f * M_PI/180.0f; SetSpeakerArrangement("layout_71CHN", SpeakerAngle, Speaker2Chan, Device->NumChan); break; } if(GetConfigValueBool(NULL, "scalemix", 0)) { ALfloat maxout = 1.0f; for(s = 0;s < MAXCHANNELS;s++) { ALfloat out = 0.0f; for(s2 = 0;s2 < MAXCHANNELS;s2++) out += Device->ChannelMatrix[s2][s]; maxout = __max(maxout, out); } maxout = 1.0f/maxout; for(s = 0;s < MAXCHANNELS;s++) { for(s2 = 0;s2 < MAXCHANNELS;s2++) Device->ChannelMatrix[s2][s] *= maxout; } } PanningLUT = Device->PanningLUT; for(pos = 0; pos < LUT_NUM; pos++) { /* clear all values */ offset = MAXCHANNELS * pos; for(s = 0; s < MAXCHANNELS; s++) PanningLUT[offset+s] = 0.0f; if(Device->NumChan == 1) { PanningLUT[offset + Speaker2Chan[0]] = 1.0f; continue; } /* source angle */ Theta = aluLUTpos2Angle(pos); /* set panning values */ for(s = 0; s < Device->NumChan - 1; s++) { if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1]) { /* source between speaker s and speaker s+1 */ Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) / (SpeakerAngle[s+1]-SpeakerAngle[s]); PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha); PanningLUT[offset + Speaker2Chan[s+1]] = sin(Alpha); break; } } if(s == Device->NumChan - 1) { /* source between last and first speaker */ if(Theta < SpeakerAngle[0]) Theta += 2.0f * M_PI; Alpha = M_PI_2 * (Theta-SpeakerAngle[s]) / (2.0f * M_PI + SpeakerAngle[0]-SpeakerAngle[s]); PanningLUT[offset + Speaker2Chan[s]] = cos(Alpha); PanningLUT[offset + Speaker2Chan[0]] = sin(Alpha); } } }
//------------------------------------------------------------------------------------------------ // function to compute data term //------------------------------------------------------------------------------------------------ void BPFlow::ComputeDataTerm() { // allocate the buffer for data term nTotalMatches = AllocateBuffer<PixelBuffer2D<T_message>, T_message>(pDataTerm, ptrDataTerm, WinSize); int XWinLength = WinSize * 2 + 1; T_message HistMin,HistMax; double HistInterval; double* pHistogramBuffer; int nBins=20000; int total=0; // total is the total number of plausible matches, used to normalize the histogram pHistogramBuffer=new double[nBins]; memset(pHistogramBuffer,0,sizeof(double)*nBins); HistMin= 32767; HistMax=0; //-------------------------------------------------------------------------------------------------- // step 1. the first sweep to compute the data term for the visible matches //-------------------------------------------------------------------------------------------------- // accelerate here! for(ptrdiff_t i = 0; i < Height; i++) // index over y for(ptrdiff_t j = 0; j < Width; j++) // index over x { size_t index = i * Width + j; // loop over a local window for(ptrdiff_t k = -WinSize; k <= WinSize; k++) // index over y for(ptrdiff_t l = -WinSize; l <= WinSize; l++) // index over x { ptrdiff_t x = j + pOffset[0][index] + l; ptrdiff_t y = i + pOffset[1][index] + k; ptrdiff_t index2 = y * Width2 + x; T_message foo = 0; // if the point is outside the image boundary then continue if(!InsideImage(x, y)) continue; // |S1(p) - S2(p + f(p))| for(int n = 0; n < nChannels; n++) foo += abs(pIm1[index * nChannels + n] - pIm2[index2 * nChannels + n]); // L1 norm pDataTerm[index][(k + WinSize) * XWinLength + l + WinSize] = foo; HistMin=__min(HistMin,foo); HistMax=__max(HistMax,foo); total++; } } // compute the histogram info HistInterval=(double)(HistMax-HistMin)/nBins; //-------------------------------------------------------------------------------------------------- // step 2. get the histogram of the matching //-------------------------------------------------------------------------------------------------- // accelerate here! for(ptrdiff_t i=0;i<Height;i++) // index over y for(ptrdiff_t j=0;j<Width;j++) // index over x { size_t index=i*Width+j; // loop over a local window for(ptrdiff_t k = -WinSize; k <= WinSize; k++) // index over y for(ptrdiff_t l = -WinSize; l <= WinSize; l++) // index over x { ptrdiff_t x = j + pOffset[0][index] + l; ptrdiff_t y = i + pOffset[1][index] + k; // if the point is outside the image boundary then continue if(!InsideImage(x,y)) continue; int foo = __min(pDataTerm[index][(k + WinSize) * XWinLength + l + WinSize] / HistInterval, nBins-1); pHistogramBuffer[foo]++; } } for(int i=0;i<nBins;i++) // normalize the histogram pHistogramBuffer[i] /= total; T_message DefaultMatchingScore; double Prob=0; for(int i=0;i<nBins;i++) { Prob+=pHistogramBuffer[i]; if(Prob>=0.5)//(double)Area/nTotalMatches) // find the matching score { DefaultMatchingScore=__max(i,1)*HistInterval+HistMin; break; } } if(IsDisplay) #ifdef INTMESSAGE printf("Min: %d, Default: %d, Max: %d\n",HistMin,DefaultMatchingScore,HistMax); #else printf("Min: %f, Default: %f, Max: %f\n",HistMin,DefaultMatchingScore,HistMax); #endif //-------------------------------------------------------------------------------------------------- // step 3. assigning the default matching score to the outside matches //-------------------------------------------------------------------------------------------------- // accelerate here! for(ptrdiff_t i=0;i<Height;i++) // index over y for(ptrdiff_t j=0;j<Width;j++) // index over x { size_t index=i*Width+j; // loop over a local window for(ptrdiff_t k = -WinSize; k <= WinSize; k++) // index over y for(ptrdiff_t l = -WinSize; l <= WinSize; l++) // index over x { ptrdiff_t x = j + pOffset[0][index] + l; ptrdiff_t y = i + pOffset[1][index] + k; int _ptr = (k + WinSize) * XWinLength + l + WinSize; // if the point is outside the image boundary then continue if(!InsideImage(x,y)) pDataTerm[index][_ptr]=DefaultMatchingScore; else if (IsDataTermTruncated) // put truncaitons to the data term pDataTerm[index][_ptr]=__min(pDataTerm[index][_ptr],DefaultMatchingScore); } } delete pHistogramBuffer; }
/** * @brief This function is the sfunc for the aggregator computing the topic * counts. It scans the topic assignments in a document and updates the word * topic counts. * @param args[0] The state variable, current topic counts * @param args[1] The unique words in the document * @param args[2] The counts of each unique word in the document * @param args[3] The topic assignments in the document * @param args[4] The size of vocabulary * @param args[5] The number of topics * @return The updated state **/ AnyType lda_count_topic_sfunc::run(AnyType & args) { if(args[4].isNull() || args[5].isNull()) throw std::invalid_argument("null parameter - voc_size and/or \ topic_num is null"); if(args[1].isNull() || args[2].isNull() || args[3].isNull()) return args[0]; int32_t voc_size = args[4].getAs<int32_t>(); int32_t topic_num = args[5].getAs<int32_t>(); if(voc_size <= 0) throw std::invalid_argument( "invalid argument - voc_size"); if(topic_num <= 0) throw std::invalid_argument( "invalid argument - topic_num"); ArrayHandle<int32_t> words = args[1].getAs<ArrayHandle<int32_t> >(); ArrayHandle<int32_t> counts = args[2].getAs<ArrayHandle<int32_t> >(); ArrayHandle<int32_t> topic_assignment = args[3].getAs<ArrayHandle<int32_t> >(); if(words.size() != counts.size()) throw std::invalid_argument( "dimensions mismatch - words.size() != counts.size()"); if(__min(words) < 0 || __max(words) >= voc_size) throw std::invalid_argument( "invalid values in words"); if(__min(counts) <= 0) throw std::invalid_argument( "invalid values in counts"); if(__min(topic_assignment) < 0 || __max(topic_assignment) >= topic_num) throw std::invalid_argument("invalid values in topics"); if((size_t)__sum(counts) != topic_assignment.size()) throw std::invalid_argument( "dimension mismatch - sum(counts) != topic_assignment.size()"); MutableArrayHandle<int64_t> state(NULL); int32_t *model; if(args[0].isNull()) { // to store a voc_size x (topic_num+1) integer matrix in // bigint[] (the +1 is for a flag of ceiling the count), // we need padding if the size is odd. // 1. when voc_size * (topic_num + 1) is (2n+1), gives (n+1) // 2. when voc_size * (topic_num + 1) is (2n), gives (n) int dims[1] = {(voc_size * (topic_num + 1) + 1) * sizeof(int32_t) / sizeof(int64_t)}; int lbs[1] = {1}; state = madlib_construct_md_array( NULL, NULL, 1, dims, lbs, INT8TI.oid, INT8TI.len, INT8TI.byval, INT8TI.align); // the reason we use bigint[] because integer[] has limit on number of // elements and thus cannot be larger than 500MB model = reinterpret_cast<int32_t *>(state.ptr()); } else { state = args[0].getAs<MutableArrayHandle<int64_t> >(); model = reinterpret_cast<int32_t *>(state.ptr()); } int32_t unique_word_count = static_cast<int32_t>(words.size()); int32_t word_index = 0; for(int32_t i = 0; i < unique_word_count; i++){ int32_t wordid = words[i]; for(int32_t j = 0; j < counts[i]; j++){ int32_t topic = topic_assignment[word_index]; if (model[wordid * (topic_num + 1) + topic] <= 2e9) { model[wordid * (topic_num + 1) + topic]++; } else { model[wordid * (topic_num + 1) + topic_num] = 1; } word_index++; } } return state; }
ERRORCODE TextFlow::rebuild_lines(FrameObjectPtr object, WORD_RANGE wrange) { ERRORCODE error; DB_RECORD_NUMBER f_record = object->get_frame_record(); FramePtr frame; DB_RECORD_NUMBER p_record; ParagraphPtr paragraph; W_INDEX w_index; TEXT_WORD_PTR wp; PCOORD line_top; LINE_PTR lp; L_INDEX l_index; PCOORD frame_extent, frame_left, tab_size; PCOORD baseline; BOOL use_white_space; FLAGS frame_flags; frame_object = object; /* // Text is flowed by placing text words into lines within a frame. // Words are flowed until the end is reached and then until words stop moving. */ if ((frame = (FramePtr)database->get_record(f_record, &error, RECORD_TYPE_Frame)) == NULL) { return error; } frame_flags = frame->get_flags(); /* // See if we need to do any stretching. */ if (frame_flags & (FRAME_FLAG_stretch_frame | FRAME_FLAG_stretch_text)) { if (frame_flags & FRAME_FLAG_stretch_frame) { SHORT error; /* Stretch the frame before flowing. */ if ((error = object->stretch_frame()) != 0) { frame->release(); if (error > 0) { error = ERRORCODE_None; } return (ERRORCODE)error; } /* Frame did not change size. Flow normally. */ } #if 0 else #else /* Always check (or check, too). */ if (frame_flags & FRAME_FLAG_stretch_text) #endif { /* Stretch the text before flowing. */ if ((error = frame->stretch_text()) != ERRORCODE_None) { frame->release(); return error; } /* Flow all the text. */ wrange.w_start = wrange.w_end = -1; } } p_record = frame->get_paragraph(); if ((paragraph = (ParagraphPtr)database->get_record(p_record, &error, RECORD_TYPE_Paragraph)) == NULL) { frame->release(); return error; } /* // Ascertain the true start and end of the text flow request. */ SHORT word_count = paragraph->number_of_words(); if (wrange.w_start < 0) { wrange.w_start = 0; } if (wrange.w_end < 0) { wrange.w_end = word_count-1; } if (wrange.w_start > wrange.w_end || wrange.w_end >= word_count) { /* Error of a parameter nature. */ paragraph->release(); frame->release(); return ERRORCODE_BadParameter; } /* // Find the line where the desired word starts. // If the word hasn't been flowed yet, it may be "between" existing lines. // If a word is not in a line, we'll shove it into the line just following it. // This should always be possible, because the EOP word should always be // flowed and in a line (and no word should come after it). // // We can do this really easily by just checking the last word in the line. // If we are before that line, we have our line. */ SHORT line_count = frame->number_of_lines(); for (lp = frame->get_line(0), l_index = 0; l_index < line_count; l_index++, lp++) { /* MH 4/25/93 this was "if (lp->w_end >= wrange.w_start)" */ if (lp->w_end + 1 >= wrange.w_start) { break; } } /* // Adjust w_start to the start of the line or our word, whichever is first. */ if (wrange.w_start > lp->w_start) { wrange.w_start = lp->w_start; } #ifdef DEBUG_RL printf("Flow words from %d to %d @ line %d\n", wrange.w_start, wrange.w_end, l_index); #endif /* // Now, we have the line (l_index) and the first word to flow (w_start) into // it. Let's do some flowin'! */ /* Compute the flowable extent and the size of a tab. */ TextStyleRef style = paragraph->get_style(); PBOX bound = frame->get_bound(); frame_left = style.get_left_margin(); frame_extent = bound.x1 - bound.x0 - (style.get_left_margin() + style.get_right_margin()); use_white_space = frame_flags & FRAME_FLAG_use_white_space; if ((tab_size = frame_extent / 16) == 0) { tab_size = 1; } /* Compute the current top of line. */ baseline = lp->baseline; line_top = baseline - lp->ascend; #ifdef DEBUG_RL printf("current baseline: %ld, ascend: %ld, line_top:%ld\n", baseline, lp->ascend, line_top); #endif for (w_index = wrange.w_start, wp = paragraph->get_word(w_index);; ) { PCOORD extent; /* Horizontal extent. */ PCOORD x_offset; /* Horizontal position. */ PCOORD solid_x_offset; LINE old_line; BOOL line_changed; #ifdef DEBUG_RL printf("(flow next line)\n"); #endif /* Remember the old line so we can tell if it moved. */ old_line = *lp; /* Start a new line. */ lp->w_start = w_index; /* Initialize the horizontal extent. */ extent = frame_extent; /* Plug in parameters for this line and update line_top. */ lp->ascend = lp->descend = lp->line_spacing = 0; baseline = line_top; /* Start us at the left margin. */ x_offset = 0; solid_x_offset = 0; /* Flow words into this line until done (possibly passing w_end). */ while (w_index < word_count) { FLAGS flags = wp->flags; /* Calculate tab width if necessary. */ if (wp->type == WORD_TYPE_tab) { wp->width = ((x_offset + tab_size)/tab_size)*tab_size - x_offset; } /* See if this word will fit in the row. */ #ifdef DEBUG_RL printf("flow word "); dump_word(paragraph, wp); printf("..."); #endif if (flags & WORD_FLAG_override) { /* Something is overridden. */ wp->flags &= ~WORD_FLAG_override; if (flags & WORD_FLAG_override_flow) { /* // A flow word! // Note that the flags have been cleared, so we won't keep // hitting this. */ break; } } else if (x_offset + wp->width > extent /* doesn't fit */ && w_index != lp->w_start /* not first word */ && !(wp->type == WORD_TYPE_space && ((wp-1)->type == WORD_TYPE_solid || (wp-1)->type == WORD_TYPE_macro)) && wp->width != 0) /* real word */ { #ifdef DEBUG_RL printf(" Move word to next line\n"); #endif break; } /* Update the horizontal offsets. */ x_offset += wp->width; if (use_white_space || wp->type == WORD_TYPE_solid || wp->type == WORD_TYPE_macro) { solid_x_offset = x_offset; } if (wp->ascend > lp->ascend) { #ifdef DEBUG_RL printf("Expand ascend from %ld to %ld\n", lp->ascend, wp->ascend); #endif baseline -= lp->ascend; baseline += (lp->ascend = wp->ascend); #ifdef DEBUG_RL printf("Baseline moves to %ld\n", baseline); #endif } if (wp->descend > lp->descend) { #ifdef DEBUG_RL printf("Expand descend from %ld to %ld\n", lp->descend, wp->descend); #endif lp->descend = wp->descend; } if (wp->line_spacing > lp->line_spacing) { lp->line_spacing = wp->line_spacing; } /* Add this word to the line. */ lp->w_end = w_index++; #ifdef DEBUG_RL printf(" Add word to line (x:%ld, w:%ld).\n", x_offset-wp->width, wp->width); #endif /* If we just placed a break word, this line is done. */ if (wp++->type == WORD_TYPE_break) { /* // If the previous word: // (a) was a "macro" word, // (b) started at the beginning of the line, and // (c) had zero width, // don't flow the break to the next line. */ BOOL fBreak = TRUE; if (w_index >= 2 && x_offset == 0) { TEXT_WORD_PTR wprev = wp-2; /* I make an assumption - x_offset == 0 --> width == 0. */ // if (wprev->width == 0) { if (*(paragraph->get_character(wprev->c_start)) >= MACRO_CHARACTER) { fBreak = FALSE; } } } if (fBreak) { #ifdef DEBUG_RL printf("(Breaking on BREAK word)\n"); #endif /* We need to break for this line. */ break; } } } #ifdef DEBUG_RL printf("[ line %d base:%ld, asc:%ld, dsc:%ld, w: %d to %d ]\n", l_index, baseline, lp->ascend, lp->descend, lp->w_start, lp->w_end); #endif /* // We now know all the words in this line. Handle the placement. */ /* First calculate the alignment offset. */ if ((x_offset = extent - solid_x_offset) > 0) { /* Some space to distribute. */ switch (style.get_line_alignment()) { case ALIGN_center: { x_offset /= 2; break; } case ALIGN_left: { x_offset = 0; break; } default: { break; } } } else { x_offset = 0; } /* Now set the positions of the words in this line. */ line_changed = FALSE; /* Cross your fingers. */ x_offset += style.get_left_margin(); { W_INDEX w_index = lp->w_start, w_end = lp->w_end; TEXT_WORD_PTR wp = paragraph->get_word(w_index); /* Redisplay variables */ TEXT_WORD_PTR first_word_change = NULL; TEXT_WORD_PTR last_word_change = NULL; PCOORD erase_xmin, erase_xmax; BOOL found_erase = FALSE; lp->refresh_xmin = 0x7fffffff; lp->refresh_xmax = -lp->refresh_xmin; while (w_index <= w_end) { if (x_offset != wp->x_offset || (wp->flags & WORD_FLAG_changed_size)) { /* A word moved. */ #ifdef DEBUG_RL printf("word %d changed from %ld to %ld\n", w_index, wp->x_offset, x_offset); #endif if (first_word_change == NULL) { first_word_change = wp; } if (!found_erase && wp->x_offset != -1 && w_index >= old_line.w_start && w_index <= old_line.w_end) { erase_xmin = wp->x_offset + wp->draw_left; erase_xmax = wp->x_offset + wp->draw_width; found_erase = TRUE; } last_word_change = wp; if (wp->x_offset != -1 && w_index >= old_line.w_start && w_index <= old_line.w_end) { erase_xmin = __min(erase_xmin, wp->x_offset + wp->draw_left); erase_xmax = __max(erase_xmax, wp->x_offset + wp->draw_width); } wp->x_offset = x_offset; //remove this to do word-wise refresh; restore it to do full line refresh // line_changed = TRUE; } wp->flags &= ~WORD_FLAG_changed_size; lp->refresh_xmin = __min(lp->refresh_xmin, wp->x_offset + wp->draw_left); lp->refresh_xmax = __max(lp->refresh_xmax, wp->x_offset + wp->draw_width); x_offset += wp++->width; w_index++; } if (first_word_change != NULL && old_line.baseline != -1) { /* Add a DRAW for every word that moved; erase moved words from their old positions. */ add_words_refresh_extent(frame, &old_line, first_word_change, last_word_change, REFRESH_DRAW); if (found_erase) { add_width_refresh_extent(frame, &old_line, erase_xmin, erase_xmax, REFRESH_ERASE); } } } /* See if the line changed. */ if (!line_changed) { /* Words stayed the same. See if the line is different somehow. */ /* Compare using the OLD_LINE structure. This allows us to ignore the changes in refresh_xmin, refresh_xmax. */ line_changed = (memcmp(&old_line, lp, sizeof(OLD_LINE)) != 0); if (line_changed) { lp->baseline = -1; } } if (line_changed) { #ifdef DEBUG_RL printf("Line %d changed\n", l_index); printf("old [%d to %d] vs. new [%d to %d]\n", old_line.w_start, old_line.w_end, lp->w_start, lp->w_end); #endif if (old_line.baseline != -1) { add_line_refresh_extent(frame, &old_line); } } else { #ifdef DEBUG_RL printf("Line %d stayed the same\n", l_index); #endif /* We can end now! */ if (w_index > wrange.w_end) { break; } } /* See if we're done. */ if (w_index >= word_count) { /* Run out of words. Finished. */ break; } /* // Move to a new line. // Add one if there are no more left. */ line_top = baseline + lp->descend; if (++l_index == frame->number_of_lines()) { /* Create a new dummy line. */ LINE line; #ifdef DEBUG_RL printf("(Create a new line)\n"); #endif line.w_start = line.w_end = 0; /* In case. */ line.baseline = -1; frame->insert_line(l_index, &line); lp = frame->get_line(l_index); } else { /* Add a refresh extent for the old line in case it's changing. */ #ifdef DEBUG_RL printf("(Move onto existing line)\n"); #endif lp++; } } #ifdef DEBUG_RL printf("Done (final l_index:%d, w_index:%d)...\n", l_index, w_index); #endif /* If we flowed all words, delete any trailing lines. */ if (w_index == word_count) { if (++l_index < frame->number_of_lines()) { while (l_index < frame->number_of_lines()) { #ifdef DEBUG_RL printf("{Delete line}"); #endif add_line_refresh_extent(frame, frame->get_line(l_index)); frame->delete_line(l_index); } #ifdef DEBUG_RL printf("\n"); #endif } } if (frame_flags & FRAME_FLAG_ystretch_frame) { position_lines(frame, style.get_vertical_alignment()); object->ystretch_frame(); } position_lines(frame, style.get_vertical_alignment()); /* // Release our objects. */ paragraph->release(TRUE); frame->release(TRUE); return ERRORCODE_None; }
/** * @brief This function is the sfunc of an aggregator computing the * perplexity. * @param args[0] The current state * @param args[1] The unique words in the documents * @param args[2] The counts of each unique words * @param args[3] The topic counts in the document * @param args[4] The model (word topic counts and corpus topic * counts) * @param args[5] The Dirichlet parameter for per-document topic * multinomial, i.e. alpha * @param args[6] The Dirichlet parameter for per-topic word * multinomial, i.e. beta * @param args[7] The size of vocabulary * @param args[8] The number of topics * @return The updated state **/ AnyType lda_perplexity_sfunc::run(AnyType & args){ ArrayHandle<int32_t> words = args[1].getAs<ArrayHandle<int32_t> >(); ArrayHandle<int32_t> counts = args[2].getAs<ArrayHandle<int32_t> >(); ArrayHandle<int32_t> doc_topic_counts = args[3].getAs<ArrayHandle<int32_t> >(); double alpha = args[5].getAs<double>(); double beta = args[6].getAs<double>(); int32_t voc_size = args[7].getAs<int32_t>(); int32_t topic_num = args[8].getAs<int32_t>(); size_t model64_size = static_cast<size_t>(voc_size * (topic_num + 1) + 1) * sizeof(int32_t) / sizeof(int64_t); if(alpha <= 0) throw std::invalid_argument("invalid argument - alpha"); if(beta <= 0) throw std::invalid_argument("invalid argument - beta"); if(voc_size <= 0) throw std::invalid_argument( "invalid argument - voc_size"); if(topic_num <= 0) throw std::invalid_argument( "invalid argument - topic_num"); if(words.size() != counts.size()) throw std::invalid_argument( "dimensions mismatch: words.size() != counts.size()"); if(__min(words) < 0 || __max(words) >= voc_size) throw std::invalid_argument( "invalid values in words"); if(__min(counts) <= 0) throw std::invalid_argument( "invalid values in counts"); if(doc_topic_counts.size() != (size_t)(topic_num)) throw std::invalid_argument( "invalid dimension - doc_topic_counts.size() != topic_num"); if(__min(doc_topic_counts, 0, topic_num) < 0) throw std::invalid_argument("invalid values in doc_topic_counts"); MutableArrayHandle<int64_t> state(NULL); if (args[0].isNull()) { ArrayHandle<int64_t> model64 = args[4].getAs<ArrayHandle<int64_t> >(); if (model64.size() != model64_size) { std::stringstream ss; ss << "invalid dimension: model64.size() = " << model64.size(); throw std::invalid_argument(ss.str()); } if(__min(model64) < 0) { throw std::invalid_argument("invalid topic counts in model"); } state = madlib_construct_array(NULL, static_cast<int>(model64.size()) + topic_num + sizeof(double) / sizeof(int64_t), INT8TI.oid, INT8TI.len, INT8TI.byval, INT8TI.align); memcpy(state.ptr(), model64.ptr(), model64.size() * sizeof(int64_t)); int32_t *_model = reinterpret_cast<int32_t *>(state.ptr()); int64_t *_total_topic_counts = reinterpret_cast<int64_t *>(state.ptr() + model64.size()); for (int i = 0; i < voc_size; i ++) { for (int j = 0; j < topic_num; j ++) { _total_topic_counts[j] += _model[i * (topic_num + 1) + j]; } } } else { state = args[0].getAs<MutableArrayHandle<int64_t> >(); } int32_t *model = reinterpret_cast<int32_t *>(state.ptr()); int64_t *total_topic_counts = reinterpret_cast<int64_t *>(state.ptr() + model64_size); double *perp = reinterpret_cast<double *>(state.ptr() + state.size() - 1); int32_t n_d = 0; for(size_t i = 0; i < words.size(); i++){ n_d += counts[i]; } for(size_t i = 0; i < words.size(); i++){ int32_t w = words[i]; int32_t n_dw = counts[i]; double sum_p = 0.0; for(int32_t z = 0; z < topic_num; z++){ int32_t n_dz = doc_topic_counts[z]; int32_t n_wz = model[w * (topic_num + 1) + z]; int64_t n_z = total_topic_counts[z]; sum_p += (static_cast<double>(n_wz) + beta) * (n_dz + alpha) / (static_cast<double>(n_z) + voc_size * beta); } sum_p /= (n_d + topic_num * alpha); *perp += n_dw * log(sum_p); } return state; }
VOID near TextFlow::add_width_refresh_extent( FramePtr frame, LINE_PTR lp, PCOORD xmin, PCOORD xmax, REFRESH_TYPE refresh_type) { if (want_refresh && database->can_refresh()) { PBOX pbox, bound = frame->get_bound(); PCOORD baseline; FLAGS object_flags = frame_object->get_flags(); if (object_flags & OBJECT_FLAG_xflipped) { pbox.x0 = bound.x1 - xmax; pbox.x1 = bound.x1 - xmin; } else { pbox.x0 = bound.x0 + xmin; pbox.x1 = bound.x0 + xmax; } if (pbox.x0 >= pbox.x1) { /* Null box */ return; } #if 0 printf("WR: %c%ld %ld%c\n", refresh_type == REFRESH_ERASE ? '(' : '[', pbox.x0, pbox.x1, refresh_type == REFRESH_ERASE ? ')' : ']'); #endif #if 0 /* Allow for pixels added by hinting and by clear-out */ pbox.x0 -= 2*redisplay_x_pixel; pbox.x1 += 2*redisplay_x_pixel; #endif baseline = lp->baseline; pbox.y0 = baseline - lp->ascend /*- 2*redisplay_y_pixel*/; pbox.y1 = baseline + lp->descend /*+ 2*redisplay_y_pixel*/; pbox.y0 = __max(pbox.y0, 0); pbox.y1 = __min(pbox.y1, bound.y1-bound.y0); if (object_flags & OBJECT_FLAG_yflipped) { PCOORD y0 = pbox.y0; pbox.y0 = bound.y1 - pbox.y1; pbox.y1 = bound.y1 - y0; } else { pbox.y0 += bound.y0; pbox.y1 += bound.y0; } RECT rExtraPixels; SetRect(&rExtraPixels, 2, 2, 2, 2); database->do_refresh_notify(&pbox, refresh_type, frame_object, &rExtraPixels); } }
BOOL CDataIndex::CreateIndex(LPCTSTR DataFileName, int Format, int Width, int Height, int NumberOfPoints, double MinX, double MaxX, double MinY, double MaxY, double MinZ, double MaxZ, BOOL Optimize) { if (m_HaveStarts) { delete [] m_CellStarts; m_HaveStarts = FALSE; } // create index for the given data file m_DataFileName = _T(DataFileName); // build index filename CFileSpec fs(DataFileName); fs.SetExt(".ldx"); // populate header values strcpy(m_Header.Signature, "LDAindex"); m_Header.Version = 1.1f; m_Header.Checksum = ComputeChecksum(DataFileName); m_Header.Format = Format; m_Header.MinX = 9999999999.0; m_Header.MinY = 9999999999.0; m_Header.MinZ = 9999999999.0; m_Header.MaxX = -9999999999.0; m_Header.MaxY = -9999999999.0; m_Header.MaxZ = -9999999999.0; m_Header.GridCellsAcross = Width; m_Header.GridCellsUp = Height; m_Header.TotalPointsIndexed = 0; // open data file CLidarData dat(DataFileName); LIDARRETURN pt; if (dat.IsValid()) { // create index file and write header m_FileHandle = fopen(fs.GetFullSpec(), "wb+"); if (m_FileHandle) { if (WriteHeader()) { if (MinX + MaxX + MinY + MaxY + MinZ + MaxZ == 0.0) { // scan data file for min/max values while (dat.ReadNextRecord(&pt)) { m_Header.MinX = __min(m_Header.MinX, pt.X); m_Header.MinY = __min(m_Header.MinY, pt.Y); m_Header.MinZ = __min(m_Header.MinZ, pt.Elevation); m_Header.MaxX = __max(m_Header.MaxX, pt.X); m_Header.MaxY = __max(m_Header.MaxY, pt.Y); m_Header.MaxZ = __max(m_Header.MaxZ, pt.Elevation); m_Header.TotalPointsIndexed ++; } dat.Rewind(); } else { // use values passed in m_Header.MinX = MinX; m_Header.MinY = MinY; m_Header.MinZ = MinZ; m_Header.MaxX = MaxX; m_Header.MaxY = MaxY; m_Header.MaxZ = MaxZ; m_Header.TotalPointsIndexed = NumberOfPoints; } // add 0.1 to max values to make sure we have a range that works for cell calculation // removed addition of 0.1 to header max values 3/21/2006 // m_Header.MaxX += 0.1; // m_Header.MaxY += 0.1; // m_Header.MaxZ += 0.1; // modified cell size calculation to add 0.1 to max data values 3/21/2006 double cellw = ((m_Header.MaxX + 0.1) - m_Header.MinX) / (double) m_Header.GridCellsAcross; double cellh = ((m_Header.MaxY + 0.1) - m_Header.MinY) / (double) m_Header.GridCellsUp; // read data file lines and build index int ptnum = 0; long offset = dat.GetPosition(); while (dat.ReadNextRecord(&pt)) { ptnum ++; m_Point.Offset = offset; m_Point.Column = (unsigned char) ((pt.X - m_Header.MinX) / cellw); m_Point.Row = (unsigned char) ((pt.Y - m_Header.MinY) / cellh); // m_Point.PointNumber = ptnum; WritePoint(); offset = dat.GetPosition(); } // rewrite the header to get min/max values and number of points WriteHeader(); // improve the index if (m_Header.TotalPointsIndexed && Optimize) { // allocate space for entire index INDEXENTRY* list = new INDEXENTRY[m_Header.TotalPointsIndexed]; if (list) { // rewind to start of index entries fseek(m_FileHandle, 128, SEEK_SET); for (int i = 0; i < m_Header.TotalPointsIndexed; i ++) { ReadPoint(); list[i].Column = m_Point.Column; list[i].Row = m_Point.Row; list[i].Offset = m_Point.Offset; } // sort list qsort(list, m_Header.TotalPointsIndexed, sizeof(INDEXENTRY), CompareIndexEntries); // re-write // rewind to start of index entries fseek(m_FileHandle, 128, SEEK_SET); for (i = 0; i < m_Header.TotalPointsIndexed; i ++) { m_Point.Column = list[i].Column; m_Point.Row = list[i].Row; m_Point.Offset = list[i].Offset; WritePoint(); } // create cell starting point file int colrow; m_CellStarts = new long[m_Header.GridCellsAcross * m_Header.GridCellsUp]; if (m_CellStarts) { // initialize starting points for (i = 0; i < m_Header.GridCellsAcross * m_Header.GridCellsUp; i ++) m_CellStarts[i] = -1; for (i = 0; i < m_Header.TotalPointsIndexed; i ++) { colrow = list[i].Column * m_Header.GridCellsUp + list[i].Row; if (m_CellStarts[colrow] < 0) m_CellStarts[colrow] = i; } // write file CFileSpec ifs(fs.GetFullSpec()); ifs.SetExt(".ldi"); FILE* f = fopen(ifs.GetFullSpec(), "wb"); if (f) { // use same header as index with slightly different signature strcpy(m_Header.Signature, "LDAstarts"); fwrite(&m_Header, sizeof(header), 1, f); // seek to end of header area fseek(f, 128, SEEK_SET); // write starting points fwrite(m_CellStarts, sizeof(long), m_Header.GridCellsAcross * m_Header.GridCellsUp, f); fclose(f); // reset header to correct signature strcpy(m_Header.Signature, "LDAindex"); } m_HaveStarts = TRUE; } delete [] list; } } fclose(m_FileHandle); // reopen in read mode and go to start of points m_FileHandle = fopen(fs.GetFullSpec(), "rb"); fseek(m_FileHandle, 128, SEEK_SET); m_Valid = TRUE; } } dat.Close(); } else { m_Valid = FALSE; } return(m_Valid); }
ERRORCODE TextFlow::adjust_words(DB_RECORD_NUMBER p_record, DB_RECORD_NUMBER f_record, CHARACTER_DELTA cdelta, WORD_DELTA_PTR wdelta) { ParagraphPtr paragraph; W_INDEX w_index; TEXT_WORD_PTR wp; ERRORCODE error; /* Redisplay vars */ LINE_PTR lp; FramePtr frame; PCOORD erase_xmin, erase_xmax; W_INDEX old_windex; L_INDEX l_index; BOOL deleted_something; /* // Initialize the word delta structure first. */ wdelta->w_start = -1; wdelta->count = 0; /* Make sure we avoid busy work. */ if (cdelta.count == 0) { return ERRORCODE_None; } /* Lock the paragraph so we can access it. */ if ((paragraph = (ParagraphPtr)database->get_record(p_record, &error, RECORD_TYPE_Paragraph)) == NULL) { return error; } /* Get the frame object. */ if ((frame = (FramePtr)database->get_record(f_record, &error, RECORD_TYPE_Frame)) == NULL) { paragraph->release(); return error; } /* // Run through the word array and update all words which need it. // We must be careful using a pointer into the word array data since any // deletions can cause the array data to change locations. */ /* Initialize redisplay variables */ deleted_something = FALSE; lp = NULL; old_windex = 0; l_index = frame->line_of_word(0, NULL); lp = (LINE_PTR)frame->line.get_element(l_index); for (wp = (TEXT_WORD_PTR)paragraph->word.get_element(0), w_index = 0; w_index < paragraph->word.count(); old_windex++, w_index++, wp++) { C_INDEX this_start; if ((this_start = wp->c_start) >= cdelta.c_start) { /* This has moved. Move it now. */ /* If deleting, see if the array is still valid. */ if ((this_start += cdelta.count) <= cdelta.c_start) { this_start = cdelta.c_start; if (!deleted_something) { deleted_something = TRUE; erase_xmin = wp->x_offset + wp->draw_left; erase_xmax = wp->x_offset + wp->draw_width; } /* // Update the word delta. // This makes the (valid) assumption that words which get // deleted are all contiguous. */ if (wdelta->w_start == -1) { wdelta->w_start = w_index; /* Start updating w1 (last word to erase) */ l_index = frame->line_of_word(w_index, NULL); lp = (LINE_PTR)frame->line.get_element(l_index); erase_xmax = __max(erase_xmax, wp->x_offset + wp->draw_width); erase_xmin = __min(erase_xmin, wp->x_offset + wp->draw_left); } else { /* The previous word has vanished. Delete it now. */ if (old_windex > lp->w_end) { /* That's all the words for this line. Erase the words */ add_width_refresh_extent(frame, lp, erase_xmin, erase_xmax, REFRESH_ERASE); /* Start a new line */ erase_xmin = wp->x_offset + wp->draw_left; erase_xmax = wp->x_offset + wp->draw_width; lp++; } else { erase_xmax = __max(erase_xmax, wp->x_offset + wp->draw_width); } wdelta->count--; /* Do the actual delete. */ paragraph->delete_word(--w_index); paragraph->modified(); #ifdef DEBUG_AW printf("Delete previous word (%d)\n", w_index); #endif /* Recompute 'wp' in case 'word.data' changed. */ wp = (TEXT_WORD_PTR)paragraph->word.get_element(w_index); } } #ifdef DEBUG_AW printf("Bumped WORD %d from index %d to %d (", w_index, wp->c_start, this_start); #endif /* Set the new start. */ wp->c_start = this_start; #ifdef DEBUG_AW dump_word(paragraph, wp); printf(")\n"); #endif } else { /* Advance the erase anchor point */ erase_xmin = __min(erase_xmin, wp->x_offset + wp->draw_left); } } if (deleted_something) { /* Found at least one line to delete. Delete the last line we found */ add_width_refresh_extent(frame, lp, erase_xmin, erase_xmax, REFRESH_ERASE); } /* Release the objects we got. */ frame->release(); paragraph->release(); return ERRORCODE_None; }
BOOL CMesh::loadFromWRL(CString sFileName) // ----- format: wrl ----- //vertex: // x y z, // ... // x y z; //face: // v1,v2,v3,...,-1, (the vertex index is 0-based) // ... // v1,v2,v3,...,-1; { //open the file FILE *f = NULL; if ((f = fopen(LPCTSTR(sFileName),"rb")) == NULL) return FALSE; _VECTORLIST VertexList;//临时存储所有点的链表 _UINTLIST FaceList;//临时存储所有面包含的点的信息 Vector3D vector; Vector3D vMin; Vector3D vMax; bool bFirst=true; char ch = ','; while(ch==',')//read vertex information { fscanf(f, "%lf%lf%lf%ch",&vector.x,&vector.y,&vector.z,&ch); VertexList.push_back(Vector3D(vector)); //计算所有点的包围盒 if(bFirst) { bFirst=false; vMin=vMax=vector; continue; } if(vector.x<vMin.x) vMin.x=vector.x; else if(vector.x>vMax.x) vMax.x=vector.x; if(vector.y<vMin.y) vMin.y=vector.y; else if(vector.y>vMax.y) vMax.y=vector.y; if(vector.z<vMin.z) vMin.z=vector.z; else if(vector.z>vMax.z) vMax.z=vector.z; } ch=','; UINT i; UINT l[MAX_VERTEX_PER_FACE]; short j; m_nFace=0; m_nEdge=0; while(ch==',')//read face information { i=0; l[0]=0; while(l[i]!=-1) fscanf(f,"%ld%c",&(l[++i]),&ch); FaceList.push_back(i-1); for (j = 1; j < i; j++) FaceList.push_back(l[j]); m_nEdge+=i-1; m_nFace++; } fclose(f); //根据包围盒将物体中心移至原点,同时进行归一化 vector=vMax-vMin; double d=__max(vector.x,vector.y); d=0.5*__max(d,vector.z); vector=0.5*(vMax+vMin);//偏移量 m_nVertex=VertexList.size(); //read vertices and faces m_pVertex = new CVertex[m_nVertex]; if (m_pVertex==NULL) {clear(); return FALSE;}//out of memory m_pFace = new CFace[m_nFace]; if (m_pFace == NULL) {clear(); return FALSE;}//out of memory _VECTORLIST::iterator iVertex = VertexList.begin(); _UINTLIST::iterator iFace = FaceList.begin(); for(i=0;i<m_nVertex;i++) m_pVertex[i].m_vPosition=(*(iVertex++)-vector)/d; short nType; for(i=0;i<m_nFace;i++) { nType=*iFace++; m_pFace[i].Create(nType); for(j=0;j<nType;j++) m_pFace[i].m_piVertex[j]=*iFace++; } VertexList.clear(); FaceList.clear(); return construct(); }
ERRORCODE TextFlow::rebuild_words(DB_RECORD_NUMBER p_record, DB_RECORD_NUMBER f_record, CHARACTER_RANGE crange, WORD_DELTA_PTR wdelta, WORD_RANGE_PTR wrange) { ParagraphPtr paragraph; FramePtr frame; W_INDEX w_index, w_start, w_end; TEXT_WORD_PTR wp; C_INDEX c_index; CHARACTER_PTR cp; ERRORCODE error; /* // Initialize the word delta structure first. */ wrange->w_start = wrange->w_end = wdelta->w_start = -1; wdelta->count = 0; /* Get the paragraph so we can operate on it. */ if ((paragraph = (ParagraphPtr)database->get_record(p_record, &error, RECORD_TYPE_Paragraph)) == NULL) { /* Error! */ return error; } /* See if there is any text. */ SHORT text_count = paragraph->number_of_characters(); if (text_count == 0) { /* No text! No words to form. */ paragraph->release(); return ERRORCODE_None; } /* Figure out where to begin forming words. */ if (crange.c_start < 0) { crange.c_start = 0; } if (crange.c_start >= text_count) { crange.c_start = text_count-1; } if (crange.c_end < 0 || crange.c_end >= text_count) { crange.c_end = text_count-1; } if (crange.c_start > crange.c_end) { /* // Huh? Bad parameters! // We could adjust the parameters to full extent and continue, but then // we might not catch a bad programming case. // Let's just return an error for now. */ od("rebuild_words: bad parameters\r\n"); paragraph->release(); return ERRORCODE_BadParameter; } /* // The first thing we need to do is go through and figure out which words // are going to be rebuilt. The first word to be rebuilt is the word containing // the start change (or the previous one if it's the first character of that // word). The c_index where word forming starts is the first character of // this word. The last word to be rebuilt is the word containing the end // change. The c_index where word forming stops is the last character of this // word. These words will be deleted and rebuilt from the c_index range // generated. */ /* // A paragraph should always have at least one word (the eop word). // OK. Here's the first problem: what happens if c_start > word(eop).c_start? // This means that the character indicies are inconsistent. This shouldn't // happen, so let's see if we can detect it and flag an error. */ /* // Look for the word containing the start offset. */ SHORT word_count = paragraph->number_of_words(); w_start = w_end = word_count; for (w_index = 0, wp = (TEXT_WORD_PTR)paragraph->word.get_element(0); w_index < word_count; wp++, w_index++) { if (wp->c_start >= crange.c_start) { w_start = w_index-1; break; } } if (w_start == word_count) { /* Couldn't find the c_index in our word array. Inconsistent. */ paragraph->release(); od("rebuild_words: start index inconsistent\r\n"); return ERRORCODE_BadParameter; } else if (w_start < 0) { /* Means c_start is in first word. */ w_start = 0; } #ifdef DEBUG_RW printf("Found start offset %d in word %d (", crange.c_start, w_start); dump_word(paragraph, (TEXT_WORD_PTR)paragraph->word.data + w_start); printf(")\n"); #endif /* Get the first index in this word. */ wrange->w_start = wrange->w_end = wdelta->w_start = w_start; if ((c_index = paragraph->get_word(w_start)->c_start) < crange.c_start) { /* Move back to start of word. */ crange.c_start = c_index; wdelta->w_start++; /* First word stays put. */ } #ifdef DEBUG_RW printf("Start offset moves to %d\n", crange.c_start); #endif /* // Look for the word containing the end offset. */ for (; w_index < word_count; wp++, w_index++) { if (wp->c_start >= crange.c_end) { w_end = w_index; break; } } if (w_end == word_count) { /* Couldn't find the c_index in our word array. Inconsistent. */ paragraph->release(); od("rebuild_words: end index inconsistent\r\n"); return ERRORCODE_IntError; } else if (w_end == word_count-1) { /* We ended up on the eop word. Move off of it. */ w_end--; } #ifdef DEBUG_RW printf("Found end offset %d in word %d (", crange.c_end, w_end); dump_word(paragraph, (TEXT_WORD_PTR)paragraph->word.data + w_end); printf(")\n"); #endif /* Get the first index of the next word. */ if ((c_index = paragraph->get_word(w_end+1)->c_start-1) > crange.c_end) { /* Move forward to end of word. */ crange.c_end = c_index; } #ifdef DEBUG_RW printf("End offset moves to %d\n", crange.c_end); #endif /* // Delete the existing range if we have one. // Perhaps this should be optimized someday to do all at once! */ if (w_end >= w_start) { /* Redisplay variables */ BOOL new_line = TRUE; L_INDEX l_index; LINE_PTR lp; TEXT_WORD_PTR wp0; PCOORD erase_xmin, erase_xmax; if ((frame = (FramePtr)database->get_record(f_record, &error, RECORD_TYPE_Frame)) == NULL) { paragraph->release(); return error; } /* Get line pointer for redisplay purposes */ l_index = frame->line_of_word(w_end, NULL); lp = frame->get_line(l_index); erase_xmin = 0x7fffffff; erase_xmax = -erase_xmin; wdelta->count = -(w_end - w_start + 1); while (w_end >= w_start) { #ifdef DEBUG_RW printf("Delete word %d\n", w_end); #endif wp0 = paragraph->get_word(w_end); if (!new_line && w_end < lp->w_start) { new_line = TRUE; add_width_refresh_extent(frame, lp, erase_xmin, erase_xmax, REFRESH_ERASE); lp--; } if (new_line) { new_line = FALSE; erase_xmin = wp0->x_offset + wp0->draw_left; erase_xmax = wp0->x_offset + wp0->draw_width; } else { erase_xmin = __min(erase_xmin, wp0->x_offset + wp0->draw_left); erase_xmax = __max(erase_xmax, wp0->x_offset + wp0->draw_width); } paragraph->delete_word(w_end--); } add_width_refresh_extent(frame, lp, erase_xmin, erase_xmax, REFRESH_ERASE); frame->release(); } /* // Start forming new words. */ for (w_index = w_start, c_index = crange.c_start, cp = paragraph->get_character(c_index); c_index <= crange.c_end; ) { TEXT_WORD word; /* Start this word. */ #ifdef DEBUG_RW printf(*cp < ' ' ? "[%d]" : "[%c]", *cp); #endif word.type = character_type(*cp++); word.flags = WORD_FLAG_needs_sizing; word.c_start = c_index++; word.x_offset = -1; word.width = 0; /* Accumulate the rest of the word. */ if (word.type == WORD_TYPE_solid) { /* Search for the next word start. */ while (c_index <= crange.c_end && character_type(*cp) == word.type) { #ifdef DEBUG_RW printf(*cp < ' ' ? "(%d)" : "(%c)", *cp); #endif cp++; c_index++; } } /* This is a whole new word. */ #ifdef DEBUG_RW printf(" ADD word %d, type %d, c (%d to %d) \n", w_index, word.type, word.c_start, c_index-1); #endif paragraph->insert_word(w_index++, &word); /* Another delta in the word array. */ wdelta->count++; wrange->w_end++; } /* Release the paragraph. */ paragraph->release(TRUE); return ERRORCODE_None; }
// Pair net. The full input is two training samples and // the target is set to 1 if the two examples have the same category // else the target is 0. The second input is randomly chosen in a two setp process: // 1) Choose a selection radius with probability probSame if the second example will be "same" // or "different" // 2) The second example is then chosen randomly from teh entire training set using the "radius" // selected in step (1) HRESULT PreProcPairInputImages(PVOID pThis, const PRE_PROCESS_DATA_ARGS *pArgs, LPCTSTR lpFile ) { static float s_probSame = 0.5; static int s_sameRadius = 3; // Note same radius is an absolute value static float s_diffRadius = 1.0F; // While Diff radius is expresed as fraction of the data set size static bool s_bInputResized = false; static bool s_bUseAutoEncoder = false; static bool s_bDoSampleSphere = false; static int s_cExtraTargetLayer = 0; static int s_cExtraInput = 0; static int s_cMaxRetry = 5; static int s_cTupleSize = 1; static TCHAR s_pairFile[MAX_PATH]; static CDataTuple *pDataTuple = NULL; HRESULT hRet = S_OK; if (NULL != lpFile) { FILE *fp; fp = _tfopen(lpFile, TEXT("r")); if (NULL != fp) { TCHAR awCmd[MAX_PATH]; TCHAR awVal[MAX_PATH]; float val; s_pairFile[0] = TEXT('\0'); s_bUseAutoEncoder = false; s_cExtraTargetLayer = 0; if (NULL != pDataTuple) { delete pDataTuple; pDataTuple = NULL; } while (2 == _ftscanf(fp, TEXT("%s %s"), awCmd, awVal)) { val = (float)_tstof(awVal); if (0 == _tcsicmp(awCmd, TEXT("probsame"))) { s_probSame = val; } else if (0 == _tcsicmp(awCmd, TEXT("sameradius"))) { s_sameRadius = (int)val; } else if (0 == _tcsicmp(awCmd, TEXT("diffradius"))) { s_diffRadius = val; } else if (0 == _tcsicmp(awCmd, TEXT("maxretry"))) { s_cMaxRetry = (int)val; } else if (0 == _tcsicmp(awCmd, TEXT("pairfile"))) { _tcscpy_s(s_pairFile, ARRAYSIZE(s_pairFile), awVal); } else if (0 == _tcsicmp(awCmd, TEXT("tuplesize"))) { s_cTupleSize = (int)val; } else if (0 == _tcsicmp(awCmd, TEXT("extrainput"))) { s_cExtraInput = (int)val; } else if (0 == _tcsicmp(awCmd, TEXT("autoencoder"))) { s_bUseAutoEncoder = true; } else if (0 == _tcsicmp(awCmd, TEXT("numextratarget"))) { s_cExtraTargetLayer = (int)val; } else if (0 == _tcsicmp(awCmd, TEXT("dosamplesphere"))) { s_bDoSampleSphere = (val == 0.0F) ? false : true; } } fclose(fp); // Did everyting load if ( s_probSame >= 0.0F && s_probSame <= 1.0F && s_sameRadius > 0 && s_diffRadius > 0 && s_diffRadius <= 1.0F ) { hRet = S_OK; s_bInputResized = false; } return hRet; } return E_INVALIDARG; } NNData *pData = (NNData *)pThis; PRE_PROCESS_DATA_ARGS *pIO = (PRE_PROCESS_DATA_ARGS*)pArgs; if (NULL == pThis || NULL == pArgs) { hRet = E_INVALIDARG; } if (SUCCEEDED(hRet) && false == s_bInputResized) { // First time around increase the size of the buffers holding inputs and its stats hRet = ResizeAllInputBuffers(pData, pIO, s_cExtraInput, s_cExtraTargetLayer, s_cTupleSize); if (SUCCEEDED(hRet)) { s_bInputResized = true; } else { return hRet; } } if (SUCCEEDED(hRet)) { if (NULL == pDataTuple && _tcslen(s_pairFile) > 0) { pDataTuple = new CDataTuple(pData->GetNumRows(), s_cTupleSize); if (!SUCCEEDED(pDataTuple->LoadFromFile(s_pairFile))) { delete pDataTuple; pDataTuple= NULL; } } int iRadius; int iOtherSamp = 0, iOtherSamp2 = 0; DREAL *pThisTarget = *(pData->GetTargetExamples() + pData->GetCurRow()); int cRetry = 0; int cOtherSamp = 1; if (NULL == pDataTuple) { DREAL *pOtherTarget; if (frand() <= s_probSame) { iRadius = s_sameRadius; do { iOtherSamp = PickOtherSamp(pData, iRadius); pOtherTarget = *(pData->GetTargetExamples() + iOtherSamp); ++cRetry; } while (*pOtherTarget != *pIO->m_pTarget && cRetry < s_cMaxRetry); } else { iRadius = (int)(s_diffRadius * pData->GetNumRows() +0.5F); do { iOtherSamp = PickOtherSamp(pData, iRadius); pOtherTarget = *(pData->GetTargetExamples() + iOtherSamp); ++cRetry; } while (*pOtherTarget == *pIO->m_pTarget && cRetry < s_cMaxRetry); } } else { TUPLE_DATA tuple; if (SUCCEEDED(pDataTuple->GetNextIdx(pData->GetCurRow(), tuple))) { int iTuple = 0; if (s_cTupleSize > 1) { CDataTuple::Shuffle(tuple.m_vPairs); iOtherSamp = tuple.m_vPairs[iTuple++]; iOtherSamp2 = tuple.m_vPairs[iTuple++]; cOtherSamp = 2; } else { iOtherSamp = tuple.m_vPairs[iTuple++]; } } } NREAL targetDiff = 0; if (cOtherSamp == 1) { targetDiff = AppendOneSample(pIO, pData, pThisTarget, iOtherSamp); } else { targetDiff = AppendTwoSamples(pIO, pData, pThisTarget, iOtherSamp, iOtherSamp2); NREAL *pSrc = pIO->m_pInput + 3*pIO->m_cInput; if (3 == s_cExtraInput) { int iSrc = 0; pSrc[iSrc++] = L1Distance(pIO->m_pInput, pIO->m_pInput + pIO->m_cInput, pIO->m_cInput); pSrc[iSrc++] = L1Distance(pIO->m_pInput, pIO->m_pInput + 2*pIO->m_cInput, pIO->m_cInput); pSrc[0] = __max(pSrc[0], 1.0F); pSrc[iSrc] = (pSrc[0] - pSrc[1]) / pSrc[0]; pSrc[iSrc] = __max(-3.0F, pSrc[iSrc]); pSrc[iSrc] = __min(3.0F, pSrc[iSrc]); pSrc[iSrc] *= 10000; if (true == s_bDoSampleSphere) { pData->SphereOneSample(pThis, pIO->m_pInput, pIO->m_cInput*3+s_cExtraInput, pData->GetMeans(), pData->GetStdev(), pData->GetInputRange(), pData->GetInputMin()); } } } if (false == s_bUseAutoEncoder) { *pIO->m_pTarget= targetDiff; } else { pIO->m_pTarget = pIO->m_pInput; pIO->m_cTarget = pIO->m_cInput; //memcpy_s(pIO->m_pTarget, pIO->m_cTarget*sizeof(*pIO->m_pTarget), pIO->m_pInput, pIO->m_cTarget*sizeof(*pIO->m_pInput)); } if (pIO->cExtraTargetLayers > 0 && NULL != pIO->m_ppExtraTargetLayers) { *pIO->m_ppExtraTargetLayers[0] = targetDiff; } hRet = S_OK; } return hRet; }
VOID TextFlow::position_lines(FramePtr frame, VERT_ALIGN_TYPE align_type) { PCOORD y_offset; L_INDEX l_index; LINE_PTR lp; PBOX refresh_offsets; PBOX bound = frame->get_bound(); PCOORD baseline; /* // Compute the height of all the lines so we can know how to align them. */ y_offset = 0; baseline = 0; SHORT line_count = frame->number_of_lines(); if (line_count == 0) { refresh_offsets.x0 = 0; refresh_offsets.x1 = 0; } else { PCOORD xmin, xmax; xmin = 0x7fffffff; xmax = -xmin; for (lp = frame->get_line(0), l_index = 0; l_index < line_count; lp++, l_index++) { xmin = __min(xmin, lp->refresh_xmin); xmax = __max(xmax, lp->refresh_xmax); if (l_index == 0) { baseline = y_offset + lp->ascend; } else { baseline = y_offset + lp->line_spacing - lp->descend; } y_offset = baseline + lp->descend; } refresh_offsets.x0 = xmin; refresh_offsets.x1 = xmax; } /* // Compute the offset value from the height of the text and the frame height. */ if ((y_offset = bound.y1 - bound.y0 - y_offset) > 0) { switch (align_type) { case ALIGN_top: { y_offset = 0; break; } case ALIGN_middle: { y_offset /= 2; break; } case ALIGN_bottom: default: { break; } } } else { /* Text too big for frame. Top align it. */ y_offset = 0; } refresh_offsets.y0 = y_offset; /* // We have the amount to offset. Do the offset now. */ for (lp = frame->get_line(0), l_index = 0; l_index < line_count; lp++, l_index++) { if (l_index == 0) { y_offset += lp->ascend; } else { y_offset += lp->line_spacing - lp->descend; } if (y_offset != lp->baseline) { if (lp->baseline != -1) { add_line_refresh_extent(frame, lp); } lp->baseline = y_offset; add_line_refresh_extent(frame, lp); } y_offset += lp->descend; } refresh_offsets.y1 = __min(y_offset, bound.y1 - bound.y0); frame->set_refresh_offsets(refresh_offsets); }
__inline float ANCHOR_IsPolyInCylinder(EERIEPOLY * ep, EERIE_CYLINDER * cyl, long flags) { if (!(flags & CFLAG_EXTRA_PRECISION)) { if (ep->area < 100.f) return 999999.f; } if (PointInCylinder(cyl, &ep->center)) { if (ep->norm.y < 0.5f) return ep->min.y; return ep->center.y; } float min = __min(cyl->origin.y, cyl->origin.y + cyl->height); float max = __max(cyl->origin.y, cyl->origin.y + cyl->height); if (min > ep->max.y) return 999999.f; if (max < ep->min.y) return 999999.f; long to; if (ep->type & POLY_QUAD) to = 4; else to = 3; long r = to - 1; float anything = 999999.f; EERIE_3D center; long n; for (n = 0; n < to; n++) { if (flags & CFLAG_EXTRA_PRECISION) { for (long o = 0; o < 5; o++) { float p = (float)o * DIV5; center.x = (ep->v[n].sx * p + ep->center.x * (1.f - p)); center.y = (ep->v[n].sy * p + ep->center.y * (1.f - p)); center.z = (ep->v[n].sz * p + ep->center.z * (1.f - p)); if (PointInCylinder(cyl, ¢er)) { anything = __min(anything, center.y); return anything; } } } if ((ep->area > 2000.f) || (flags & CFLAG_EXTRA_PRECISION) ) { center.x = (ep->v[n].sx + ep->v[r].sx) * DIV2; center.y = (ep->v[n].sy + ep->v[r].sy) * DIV2; center.z = (ep->v[n].sz + ep->v[r].sz) * DIV2; if (PointInCylinder(cyl, ¢er)) { anything = __min(anything, center.y); return anything; } if ((ep->area > 4000.f) || (flags & CFLAG_EXTRA_PRECISION)) { center.x = (ep->v[n].sx + ep->center.x) * DIV2; center.y = (ep->v[n].sy + ep->center.y) * DIV2; center.z = (ep->v[n].sz + ep->center.z) * DIV2; if (PointInCylinder(cyl, ¢er)) { anything = __min(anything, center.y); return anything; } } if ((ep->area > 6000.f) || (flags & CFLAG_EXTRA_PRECISION)) { center.x = (center.x + ep->v[n].sx) * DIV2; center.y = (center.y + ep->v[n].sy) * DIV2; center.z = (center.z + ep->v[n].sz) * DIV2; if (PointInCylinder(cyl, ¢er)) { anything = __min(anything, center.y); return anything; } } } if (PointInCylinder(cyl, (EERIE_3D *)&ep->v[n])) { anything = __min(anything, ep->v[n].sy); return anything; } r++; if (r >= to) r = 0; } if ((anything != 999999.f) && (ep->norm.y < 0.1f) && (ep->norm.y > -0.1f)) anything = __min(anything, ep->min.y); return anything; }
template<class T> static T __max(ArrayHandle<T> ah){ return __max(ah, 0, ah.size()); }
void TCPConnection::HandleIncoming(uint8_t* packet, uint64_t bytes, uint64_t HeaderSize) { // at this stage the checksum should be verified (and set to zero), so we can ignore that. TCPPacket* tcp = (TCPPacket*) packet; HeaderSize *= 4; // check if we got options. if(HeaderSize > sizeof(TCPPacket)) { uint64_t optsize = HeaderSize - sizeof(TCPPacket); uint64_t offset = sizeof(TCPPacket); while(offset < optsize) { switch(packet[offset]) { case 2: this->maxsegsize = SwapEndian16(*(packet + offset + 2)); offset += 4; break; } } } // check if ack. if(!(tcp->Flags & 0x10)) { Log("TCP ACK flag not set, discarding."); return; } uint64_t datalength = bytes - HeaderSize; this->lastpackettime = Time::Now(); this->nextack = SwapEndian32(tcp->sequence) + (uint32_t) datalength; this->servercumlsequence += __max(datalength, 1); this->PacketReceived = true; switch(this->state) { case ConnectionState::Disconnected: { Log(1, "TCP Stack error: Received packet from closed connection"); return; } case ConnectionState::WatingSYNReply: { // check if we're synchronising if(tcp->Flags & 0x2) { this->serversequence = SwapEndian32(tcp->sequence); this->servercumlsequence = 1; this->localcumlsequence = 1; this->nextack = 1; } break; } case ConnectionState::WaitingConnectionACK: { // handshake complete. Log("Established connection to %d.%d.%d.%d : %d; Relative local seq: %d, Relative server seq: %d", this->destip4.b1, this->destip4.b2, this->destip4.b3, this->destip4.b4, this->serverport, this->localcumlsequence, this->servercumlsequence); this->state = ConnectionState::Connected; break; } // disconnections: case ConnectionState::WaitingDisconnectACK: { // servers will either send an 'ACK', followed by a 'FIN, then ACK', or a 'FIN, ACK' directly. // handle both cases. if(tcp->Flags & 0x1 && tcp->Flags & 0x10) { // this is a FIN, ACK // don't respond. this->state = ConnectionState::Disconnected; return; } else if(tcp->Flags & 0x10) { // server sent an ACK, expect stuff later this->state = ConnectionState::WaitingDisconnectFINACK; return; } else { Log(1, "Invalid TCP response to FIN, ACK; state machine broken."); } break; } case ConnectionState::WaitingDisconnectFINACK: { // well we're expecting a FIN, ACK. if(tcp->Flags & 0x1 && tcp->Flags & 0x10) { this->nextack++; this->SendPacket(0, 0, 0x10); this->state = ConnectionState::Disconnected; Log("Disconnected from %d.%d.%d.%d : %d.", this->destip4.b1, this->destip4.b2, this->destip4.b3, this->destip4.b4, this->serverport); return; } else { Log(1, "Invalid TCP response to FIN, ACK; state machine broken."); } break; } case ConnectionState::Connected: { // first check if the server wants us to D/C if(tcp->Flags & 0x1) { // damn it, that f****r // send an ACK to that. this->nextack++; this->SendPacket(0, 0, 0x10); this->state = ConnectionState::WaitingDisconnectACK; return; } this->AlreadyAcked = false; // copy the packet data to the correct place. if(datalength > 0 && tcp->Flags & 0x8) { // push. // fine, bastard. uint64_t offset = SwapEndian32(tcp->sequence) - this->serversequence - 1; this->socket->recvbuffer.MoveWritePointer(offset); this->socket->recvbuffer.Write(packet + HeaderSize, datalength); Log("pushed %d bytes to offset %d", datalength, offset); } else if(datalength > 0 && (SwapEndian32(tcp->sequence) >= this->servercumlsequence) && (this->bufferfill + datalength) < TCP_MAXWINDOW) { uint64_t offset = SwapEndian32(tcp->sequence) - this->serversequence - 1; // uint64_t prp = this->packetbuffer->GetWritePointer(); Log("Copying %d bytes to offset %d", datalength, offset); this->socket->recvbuffer.MoveWritePointer(offset); this->socket->recvbuffer.Write(packet + HeaderSize, datalength); this->bufferfill += datalength; } else if((this->bufferfill + (bytes - HeaderSize)) >= TCP_MAXWINDOW) { // shit. // push data to application, // send collective ACK. HALT(""); // flush tcp to application. uint8_t* buf = new uint8_t[GLOBAL_MTU]; this->packetbuffer.Read(buf, GLOBAL_MTU); this->socket->recvbuffer.Write(buf, GLOBAL_MTU); delete[] buf; } break; } } }
/** * @brief This function learns the topics of words in a document and is the * main step of a Gibbs sampling iteration. The word topic counts and * corpus topic counts are passed to this function in the first call and * then transfered to the rest calls through args.mSysInfo->user_fctx for * efficiency. * @param args[0] The unique words in the documents * @param args[1] The counts of each unique words * @param args[2] The topic counts and topic assignments in the document * @param args[3] The model (word topic counts and corpus topic * counts) * @param args[4] The Dirichlet parameter for per-document topic * multinomial, i.e. alpha * @param args[5] The Dirichlet parameter for per-topic word * multinomial, i.e. beta * @param args[6] The size of vocabulary * @param args[7] The number of topics * @param args[8] The number of iterations (=1:training, >1:prediction) * @return The updated topic counts and topic assignments for * the document **/ AnyType lda_gibbs_sample::run(AnyType & args) { ArrayHandle<int32_t> words = args[0].getAs<ArrayHandle<int32_t> >(); ArrayHandle<int32_t> counts = args[1].getAs<ArrayHandle<int32_t> >(); MutableArrayHandle<int32_t> doc_topic = args[2].getAs<MutableArrayHandle<int32_t> >(); double alpha = args[4].getAs<double>(); double beta = args[5].getAs<double>(); int32_t voc_size = args[6].getAs<int32_t>(); int32_t topic_num = args[7].getAs<int32_t>(); int32_t iter_num = args[8].getAs<int32_t>(); size_t model64_size = static_cast<size_t>(voc_size * (topic_num + 1) + 1) * sizeof(int32_t) / sizeof(int64_t); if(alpha <= 0) throw std::invalid_argument("invalid argument - alpha"); if(beta <= 0) throw std::invalid_argument("invalid argument - beta"); if(voc_size <= 0) throw std::invalid_argument( "invalid argument - voc_size"); if(topic_num <= 0) throw std::invalid_argument( "invalid argument - topic_num"); if(iter_num <= 0) throw std::invalid_argument( "invalid argument - iter_num"); if(words.size() != counts.size()) throw std::invalid_argument( "dimensions mismatch: words.size() != counts.size()"); if(__min(words) < 0 || __max(words) >= voc_size) throw std::invalid_argument( "invalid values in words"); if(__min(counts) <= 0) throw std::invalid_argument( "invalid values in counts"); int32_t word_count = __sum(counts); if(doc_topic.size() != (size_t)(word_count + topic_num)) throw std::invalid_argument( "invalid dimension - doc_topic.size() != word_count + topic_num"); if(__min(doc_topic, 0, topic_num) < 0) throw std::invalid_argument("invalid values in topic_count"); if( __min(doc_topic, topic_num, word_count) < 0 || __max(doc_topic, topic_num, word_count) >= topic_num) throw std::invalid_argument( "invalid values in topic_assignment"); if (!args.getUserFuncContext()) { ArrayHandle<int64_t> model64 = args[3].getAs<ArrayHandle<int64_t> >(); if (model64.size() != model64_size) { std::stringstream ss; ss << "invalid dimension: model64.size() = " << model64.size(); throw std::invalid_argument(ss.str()); } if (__min(model64) < 0) { throw std::invalid_argument("invalid topic counts in model"); } int32_t *context = static_cast<int32_t *>( MemoryContextAllocZero( args.getCacheMemoryContext(), model64.size() * sizeof(int64_t) + topic_num * sizeof(int64_t))); memcpy(context, model64.ptr(), model64.size() * sizeof(int64_t)); int32_t *model = context; int64_t *running_topic_counts = reinterpret_cast<int64_t *>( context + model64_size * sizeof(int64_t) / sizeof(int32_t)); for (int i = 0; i < voc_size; i ++) { for (int j = 0; j < topic_num; j ++) { running_topic_counts[j] += model[i * (topic_num + 1) + j]; } } args.setUserFuncContext(context); } int32_t *context = static_cast<int32_t *>(args.getUserFuncContext()); if (context == NULL) { throw std::runtime_error("args.mSysInfo->user_fctx is null"); } int32_t *model = context; int64_t *running_topic_counts = reinterpret_cast<int64_t *>( context + model64_size * sizeof(int64_t) / sizeof(int32_t)); int32_t unique_word_count = static_cast<int32_t>(words.size()); for(int32_t it = 0; it < iter_num; it++){ int32_t word_index = topic_num; for(int32_t i = 0; i < unique_word_count; i++) { int32_t wordid = words[i]; for(int32_t j = 0; j < counts[i]; j++){ int32_t topic = doc_topic[word_index]; int32_t retopic = __lda_gibbs_sample( topic_num, topic, doc_topic.ptr(), model + wordid * (topic_num + 1), running_topic_counts, alpha, beta); doc_topic[word_index] = retopic; doc_topic[topic]--; doc_topic[retopic]++; if(iter_num == 1) { if (model[wordid * (topic_num + 1) + retopic] <= 2e9) { running_topic_counts[topic] --; running_topic_counts[retopic] ++; model[wordid * (topic_num + 1) + topic]--; model[wordid * (topic_num + 1) + retopic]++; } else { model[wordid * (topic_num + 1) + topic_num] = 1; } } word_index++; } } } return doc_topic; }
void CGraphPanel::AddPoint(SGraphChange* sgc) { //get main view pointer if (sgc->main_wnd_ptr == NULL) return; SSinglePoint ssp; CGraphProps* sgp = sgc->main_wnd_ptr->GetGraph(sgc->graphnum); if (!sgp->IsVisible()) { //if graph is not visible - do not do anything here return; }; sgp->GetPoint(sgc->index, &ssp); BOOL bNeedRedraw = FALSE; if ((unsigned long)(m_grflags & GRAPH_AUTOSCALE)) { //if grafix is autoscaled - just recalc coordinates and redraw the window if (ssp.x<__min(GetX1(), GetX2())) { SetMinX(ssp.x, FALSE); bNeedRedraw = TRUE; }; if (ssp.x>__max(GetX1(), GetX2())) { SetMaxX(ssp.x, FALSE); bNeedRedraw = TRUE; }; if (ssp.y<__min(GetY1(), GetY2())) { SetMinY(ssp.y, FALSE); bNeedRedraw = TRUE; }; if (ssp.y>__max(GetY1(), GetY2())) { SetMaxY(ssp.y, FALSE); bNeedRedraw = TRUE; }; }; //draw new point if (bNeedRedraw) { if (sgc->bRedraw) { UpdateGraphWindow(NULL); }; return; }; if (!sgc->bRedraw || offscreen == NULL) return; //if point is inside the graph - we need invalidate the whole picture if (sgc->index!=0 && sgc->index!=sgp->GetSize()-1) { if (sgc->bRedraw) { UpdateGraphWindow(NULL); }; return; }; int x, y, x1, y1; x = (int)CurrentCoordsX->WtoX(ssp.x); y = (int)CurrentCoordsY->WtoX(ssp.y); CDC* dc = offscreen->GetDibCDC(); if (dc != NULL) { CDC* cdc = GetDC(); CPen* pen = sgp->GetPen(); CBrush* brush = sgp->GetBrush(); CPen* oldpen = (CPen*)dc->SelectObject(pen); CBrush* oldbrush = (CBrush*)dc->SelectObject(brush); if (sgp->GetSize()>1) { if (sgc->index == 0) sgp->GetPoint(1, &ssp); if (sgc->index == sgp->GetSize()-1) sgp->GetPoint(sgc->index-1, &ssp); x1 = (int)CurrentCoordsX->WtoX(ssp.x); y1 = (int)CurrentCoordsY->WtoX(ssp.y); if (x != x1 || y != y1) { if ((m_grflags & GRAPH_GRAPH_SCATTER) == 0) { dc->MoveTo(x, y); dc->LineTo(x1, y1); }; if ((m_grflags & GRAPH_SQUAREPOINTS) != 0) { DrawSquarePoint(dc, x, y); }; CRect update_rect(x, y, x1, y1); update_rect.NormalizeRect(); update_rect.InflateRect(GetSquareSide(dc) + 2, GetSquareSide(dc) + 2); DoRedraw(cdc, update_rect); }; } else { if ((m_grflags & GRAPH_SQUAREPOINTS) != 0) { DrawSquarePoint(dc, x, y); CRect update_rect(x, y, x, y); update_rect.NormalizeRect(); update_rect.InflateRect(GetSquareSide(dc) + 2, GetSquareSide(dc) + 2); DoRedraw(cdc, update_rect); }; }; dc->SelectObject(oldpen); dc->SelectObject(oldbrush); sgp->ReleasePen(pen); sgp->ReleaseBrush(brush); ReleaseDC(cdc); }; }
//------------------------------------------------------------------------------------------------ // update the message from (x0,y0,plane) to the neighbors on the same plane // the encoding of the direction // 2 | // v // 0 ------> <------- 1 // ^ // 3 | //------------------------------------------------------------------------------------------------ void BPFlow::UpdateSpatialMessage(int x, int y, int plane, int direction) { // eliminate impossible messages if (direction==0 && x==Width-1) return; if (direction==1 && x==0) return; if (direction==2 && y==Height-1) return; if (direction==3 && y==0) return; int offset=y*Width+x; int nStates=pWinSize[plane][offset]*2+1; T_message* message_org; message_org=new T_message[nStates]; int x1=x,y1=y; // get the destination switch(direction){ case 0: x1++; s=Im_s.data()[offset*2+plane]; d=Im_d.data()[offset*2+plane]; break; case 1: x1--; s=Im_s.data()[(offset-1)*2+plane]; d=Im_d.data()[(offset-1)*2+plane]; break; case 2: y1++; s=Im_s.data()[offset*2+plane]; d=Im_d.data()[offset*2+plane]; break; case 3: y1--; s=Im_s.data()[(offset-Width)*2+plane]; d=Im_d.data()[(offset-Width)*2+plane]; break; } //s=m_s; //d=m_d; int offset1=y1*Width+x1; int nStates1=pWinSize[plane][offset1]*2+1; // get the number of states for the destination node int wsize=pWinSize[plane][offset]; int wsize1=pWinSize[plane][offset1]; T_message*& message=pSpatialMessage[plane][offset1*nNeighbors+direction].data(); // initialize the message from the dual plane if(!IsTRW) memcpy(message_org,pDualMessage[plane][offset].data(),sizeof(T_message)*nStates); else { memset(message_org,0,sizeof(T_message)*nStates); Add2Message(message_org,pDualMessage[plane][offset].data(),nStates,CTRW); } // add the range term if(!IsTRW) Add2Message(message_org,pRangeTerm[plane][offset].data(),nStates); else Add2Message(message_org,pRangeTerm[plane][offset].data(),nStates,CTRW); // add spatial messages if(!IsTRW) { if(x>0 && direction!=1) // add left to right Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates); if(x<Width-1 && direction!=0) // add right to left Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates); if(y>0 && direction!=3) // add top down Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates); if(y<Height-1 && direction!=2) // add bottom up Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates); } else { if(x>0) // add left to right if(direction==1) Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates,CTRW-1); else Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors].data(),nStates,CTRW); if(x<Width-1) // add right to left if(direction==0) Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates,CTRW-1); else Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+1].data(),nStates,CTRW); if(y>0) // add top down if(direction==3) Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates,CTRW-1); else Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+2].data(),nStates,CTRW); if(y<Height-1) // add bottom up if(direction==2) Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates,CTRW-1); else Add2Message(message_org,pSpatialMessage[plane][offset*nNeighbors+3].data(),nStates,CTRW); } // use distance transform function to impose smoothness compatibility T_message Min=CStochastic::Min(nStates,message_org)+d; for(ptrdiff_t l=1;l<nStates;l++) message_org[l]=__min(message_org[l],message_org[l-1]+s); for(ptrdiff_t l=nStates-2;l>=0;l--) message_org[l]=__min(message_org[l],message_org[l+1]+s); // transform the compatibility int shift=pOffset[plane][offset1]-pOffset[plane][offset]; if(abs(shift)>wsize+wsize1) // the shift is too big that there is no overlap { if(offset>0) for(ptrdiff_t l=0;l<nStates1;l++) message[l]=l*s; else for(ptrdiff_t l=0;l<nStates1;l++) message[l]=-l*s; } else { int start=__max(-wsize,shift-wsize1); int end=__min(wsize,shift+wsize1); for(ptrdiff_t i=start;i<=end;i++) message[i-shift+wsize1]=message_org[i+wsize]; if(start-shift+wsize1>0) for(ptrdiff_t i=start-shift+wsize1-1;i>=0;i--) message[i]=message[i+1]+s; if(end-shift+wsize1<nStates1) for(ptrdiff_t i=end-shift+wsize1+1;i<nStates1;i++) message[i]=message[i-1]+s; } // put back the threshold for(ptrdiff_t l=0;l<nStates1;l++) message[l]=__min(message[l],Min); // normalize the message by subtracting the minimum value Min=CStochastic::Min(nStates1,message); for(ptrdiff_t l=0;l<nStates1;l++) message[l]-=Min; delete message_org; }