repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jayce-incognito/leapxpert-test-fe
src/components/Icons/Infinite.tsx
import React from 'react'; import styled from 'styled-components'; interface IProps {} const Styled = styled.button` width: 20px; height: 11px; `; const InfiniteVector = React.memo((props: any) => { return ( <svg width={20} height={11}> <path d="M15.53 9.216c2.557 0 4.285-1.78 4.285-4.504 0-2.725-1.728-4.504-4.284-4.504-1.34 0-2.49.563-3.72 1.757L10.06 3.65 8.316 1.965C7.086.771 5.936.208 4.596.208 2.04.208.31 1.988.31 4.712c0 2.725 1.729 4.504 4.285 4.504 1.34 0 2.49-.571 3.72-1.758l1.744-1.691 1.75 1.691c1.23 1.187 2.38 1.758 3.72 1.758zM4.597 7.656C2.977 7.656 1.87 6.5 1.87 4.712c0-1.795 1.106-2.944 2.725-2.944.893 0 1.699.432 2.63 1.303l1.742 1.64-1.75 1.642c-.923.871-1.729 1.303-2.622 1.303zm10.935 0c-.894 0-1.7-.432-2.622-1.303l-1.75-1.641 1.742-1.64c.93-.872 1.729-1.304 2.63-1.304 1.618 0 2.724 1.15 2.724 2.944 0 1.787-1.106 2.944-2.724 2.944z" fill="#000" fillRule="nonzero" {...props} /> </svg> ); }); const Infinite = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { const { className = '' } = props; return ( <Styled type="button" className={`icon ${className || ''}`} {...props}> <InfiniteVector /> </Styled> ); }; export default Infinite;
jayce-incognito/leapxpert-test-fe
src/module/Home/Home.reducer.ts
<reponame>jayce-incognito/leapxpert-test-fe export interface IReducer {} const initialState: IReducer = {}; const reducer = ( state = initialState, action: { type: string; payload: any; }, ) => { switch (action.type) { case '': { return { ...state, }; } default: return state; } }; export default reducer;
jayce-incognito/leapxpert-test-fe
src/module/Todo/Todo.list.tsx
import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { ButtonRemove, TyniButton } from 'src/components/Core'; import { COLORS } from 'src/styles'; import styled from 'styled-components'; import { actionChangeStatus, TODO_STATUS } from '.'; import { actionRemoveTodo } from './Todo.actions'; import { ITodo } from './Todo.interface'; import { listTodoSelector } from './Todo.selector'; const Styled = styled.div` margin: 24px 0; height: 200px; overflow-x: hidden; overflow-y: scroll; .todo-item { height: 40px; border-bottom: solid 1px ${COLORS.colorGreyLight}; :last-child { border-bottom: solid 1px transparent; } } .todo-item .todo-item-value { flex: 1; margin-right: 15px; } .todo-item .item-done { text-decoration: line-through; } .todo-item .todo-item-btn { } `; const TodoItem = React.memo((props: { todo: ITodo }) => { const dispatch = useDispatch(); const { todo } = props; if (!todo || !todo.id) { return null; } const { id, value, status } = todo; const handleRemoveTodo = () => { dispatch(actionRemoveTodo(id)); }; const handleChangeStatus = () => { let _status = -1; switch (status) { case TODO_STATUS.ACTIVE: _status = TODO_STATUS.DONE; break; case TODO_STATUS.DONE: _status = TODO_STATUS.ACTIVE; break; default: break; } dispatch(actionChangeStatus({ ...todo, status: _status })); }; return ( <div className="todo-item hook-row-space-between"> <div className={`todo-item-value fs-medium pointer ${status === TODO_STATUS.DONE ? 'item-done' : ''}`} onClick={handleChangeStatus} > {value} </div> <ButtonRemove className="todo-item-btn btn-remove" onClick={handleRemoveTodo} /> </div> ); }); const TodoList = () => { const list = useSelector(listTodoSelector); if (!list) { return null; } return ( <Styled className="todo-list"> {list.map((todo) => ( <TodoItem key={todo?.id} todo={todo} /> ))} </Styled> ); }; export default React.memo(TodoList);
jayce-incognito/leapxpert-test-fe
src/components/Templates/Templates.actions.ts
import { ACTION_FETCHED } from './Templates.constant'; export const actionFetched = (payload: any) => ({ type: ACTION_FETCHED, payload, });
jayce-incognito/leapxpert-test-fe
src/i18n/en.ts
<reponame>jayce-incognito/leapxpert-test-fe import { ILanguage } from './interface'; const language: ILanguage = { general: { copied: 'Copied', copy: 'Copy', seeKey: 'See keys', lostNetwork: 'Your internet connection is currently<br />unstable. Please check your network<br />settings and try again.', btnReload: 'Reload', loadingTx: `Please do not navigate away till this<br />window closes.`, btnRetry: 'Retry', switched: 'Switched', removed: 'Removed', keys: 'keys', readyDesc: 'You’re ready to go Incognito.', hasCameraDesc: 'To continue using Incognito, please close this window and reopen the extension.', scanQrCode: 'Scan QR Code', placeQrCode: 'Place the QR code in front of your camera', cameraReadyDesc: 'Scan function enabled.', success: 'Success', masterKey: 'Master keys', masterLess: 'Masterless', keychainName: 'Keychain name', masterKeyName: 'Master key name', privateKey: 'Private key', phrase: 'Phrase', btnSetting: 'Setting', btnTrash: 'Clear', }, setting: { headerTitle: 'Settings', network: { title: 'Network', }, dev: { title: 'Dev Sections', homeConfigs: 'Use staging home configs', }, addressBook: { title: 'Address Book', desc: 'Manage your saved addresses', }, keychain: { title: 'Keychain', desc: 'Manage your keychains', }, decimalDigits: { title: 'Decimal Digits', desc: 'Limit main asset<br />displays to 5 decimal digits', }, darkMode: { title: 'Theme', desc: 'Use dark mode and light mode', }, logout: { title: 'Logout', }, }, }; export default language;
jayce-incognito/leapxpert-test-fe
src/services/server.ts
export const MAINNET_FULLNODE = 'https://lb-fullnode.incognito.org/fullnode'; export const TESTNET_FULLNODE = 'https://testnet.incognito.org/fullnode'; export const TESTNET1_FULLNODE = 'http://172.16.17.32:20002/fullnode'; export const PRODUCTION_API = 'https://api-service.incognito.org'; export const STAGING_API = 'https://staging-api-service.incognito.org'; export const PRODUCTION_API_2 = 'https://device-network.incognito.org'; export const STAGING_API_2 = 'https://device-network-staging.incognito.org'; export interface IServer { id: string; default?: boolean; address: string; name: string; chainURL: string; apiURL: string; exploreChainURL: string; api2URL: string; exploreBinanceURL: string; etherscanURL: string; } export const TEST_NODE_SERVER = { id: 'testnode', default: false, address: 'http://192.168.127.12:6354', name: 'Test Node', }; export const MAINNET_SERVER: IServer = { id: 'mainnet', default: true, address: MAINNET_FULLNODE, name: 'Mainnet', chainURL: MAINNET_FULLNODE, apiURL: PRODUCTION_API, api2URL: PRODUCTION_API_2, exploreChainURL: 'https://mainnet.incognito.org', exploreBinanceURL: 'https://explorer.binance.org', etherscanURL: 'https://etherscan.io', }; export const TESTNET_SERVER: IServer = { id: 'testnet', default: false, address: TESTNET_FULLNODE, name: 'Testnet', chainURL: TESTNET_FULLNODE, apiURL: STAGING_API, api2URL: STAGING_API_2, exploreChainURL: 'https://testnet.incognito.org', exploreBinanceURL: 'https://testnet-explorer.binance.org', etherscanURL: 'https://kovan.etherscan.io', }; export const LOCAL_SERVER: IServer = { id: 'local', default: false, address: 'http://localhost:9334', name: 'Local', chainURL: '', apiURL: '', api2URL: '', exploreChainURL: '', exploreBinanceURL: '', etherscanURL: '', }; export const TEST_NET_1_SERVER = { id: 'testnet1', default: false, address: TESTNET1_FULLNODE, name: 'Testnet 1', }; export const DEFAULT_LIST_SERVER = [ // LOCAL_SERVER, MAINNET_SERVER, TESTNET_SERVER, ];
jayce-incognito/leapxpert-test-fe
src/components/Icons/ClockWise.tsx
<reponame>jayce-incognito/leapxpert-test-fe import React from 'react'; import { ENVS } from 'src/configs'; import styled from 'styled-components'; interface IProps {} const Styled = styled.button` width: 40px; height: 40px; `; const ClockWise = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { return ( <Styled className="icon" {...props}> <img src={`${ENVS.REACT_APP_DOMAIN_URL}/images/icons/clockwise.png`} alt="" /> </Styled> ); }; export default ClockWise;
jayce-incognito/leapxpert-test-fe
src/module/MainRoute/index.ts
import MainRoute from './MainRoute'; export default MainRoute;
jayce-incognito/leapxpert-test-fe
src/components/Icons/AddCircle.tsx
<reponame>jayce-incognito/leapxpert-test-fe<filename>src/components/Icons/AddCircle.tsx import React from 'react'; import styled from 'styled-components'; interface IProps {} const Styled = styled.button` width: 19px; height: 19px; `; const AddCircleVector = React.memo((props: any) => { return ( <svg width={19} height={19}> <path d="M9.538 18.62c4.904 0 8.965-4.07 8.965-8.966 0-4.904-4.07-8.965-8.974-8.965C4.634.69.573 4.75.573 9.654c0 4.896 4.07 8.965 8.965 8.965zm-.017-4.738c-.449 0-.756-.325-.756-.774V10.41H6.084c-.457 0-.782-.299-.782-.747 0-.457.316-.773.782-.773h2.68V6.2c0-.457.308-.782.757-.782.457 0 .773.325.773.782v2.69h2.698c.448 0 .765.316.765.773 0 .448-.317.747-.765.747h-2.698v2.698c0 .449-.316.774-.773.774z" fill="#000" fillRule="nonzero" {...props} /> </svg> ); }); const AddCircle = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { return ( <Styled className="icon" {...props}> <AddCircleVector /> </Styled> ); }; export default AddCircle;
jayce-incognito/leapxpert-test-fe
src/hooks/useDetectClickOutside.tsx
import React from 'react'; const useOutsideRef = (ref: any, callback?: () => any) => { const handleClickOutside = (event: MouseEvent) => { if (typeof ref?.current?.contains === 'function' && !ref?.current?.contains(event.target)) { if (typeof callback === 'function') { callback(); } } }; React.useEffect(() => { document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, [ref, callback]); }; export default useOutsideRef;
jayce-incognito/leapxpert-test-fe
src/module/Todo/Todo.enhance.tsx
import React from 'react'; import { compose } from 'recompose'; import ErrorBoundary from 'src/components/ErrorBoundary'; interface IProps {} const enhance = (WrappedComponent: React.FunctionComponent) => (props: IProps) => { return ( <ErrorBoundary> <WrappedComponent {...props} /> </ErrorBoundary> ); }; export default compose<IProps, any>(enhance);
jayce-incognito/leapxpert-test-fe
src/components/Header/index.ts
<reponame>jayce-incognito/leapxpert-test-fe export { default } from './Header'; export { default as HeaderApp } from './Header.headerApp';
jayce-incognito/leapxpert-test-fe
src/module/Setting/index.ts
<gh_stars>0 export { default } from './Setting'; export * from './Setting.actions'; export * from './Setting.constant'; export * from './Setting.reducer'; export * from './Setting.selector'; export * from './Setting.route'; export * from './Setting.interface';
jayce-incognito/leapxpert-test-fe
src/components/Icons/LostConnect.tsx
<gh_stars>0 import React from 'react'; import styled from 'styled-components'; interface IProps {} const Styled = styled.button` width: 60px; height: 60px; `; const LostConnectVector = React.memo((props: any) => { return ( <svg width="60px" height="60px" viewBox="0 0 62 62"> <g transform="translate(1 1)" fill="none" fillRule="evenodd" {...props}> <circle stroke="#E9E8E8" strokeWidth={2} cx={30} cy={30} r={30} /> <path d="M30.515 35.946c.586 0 .996-.395 1.01-1.01l.088-17.242c0-.644-.498-1.069-1.113-1.069s-1.113.425-1.113 1.07c.044 5.742.073 11.498.117 17.24 0 .616.41 1.011 1.01 1.011zm-13.726-7.602c2.857-3.018 6.504-4.922 10.562-5.537l-.03-4.175c-5.449.79-10.488 3.442-13.388 7.016-.19.235-.176.542.044.791l1.919 1.92c.263.263.63.263.893-.015zm28.315 0l1.905-1.905c.249-.249.234-.556.044-.79-2.93-3.545-7.91-6.255-13.389-7.017l-.03 4.175c4.058.586 7.706 2.505 10.592 5.551.249.264.615.25.878-.014zm-6.079 6.123l2.154-2.139c.22-.22.249-.527.044-.762-1.656-2.036-4.453-3.662-7.603-4.277l-.03 4.35c1.773.543 3.385 1.568 4.556 2.828.264.278.586.263.88 0zm-16.128-.044c1.143-1.26 2.754-2.256 4.512-2.813l-.03-4.32c-3.163.644-5.917 2.226-7.616 4.276-.19.235-.176.528.058.762l2.154 2.153c.293.279.644.25.922-.058zm7.603 7.822a2.022 2.022 0 002.021-2.007 2.026 2.026 0 00-2.021-2.021 2.013 2.013 0 000 4.028z" fill="#8A8A8E" fillRule="nonzero" /> </g> </svg> ); }); const LostConnect = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { return ( <Styled className="icon" {...props}> <LostConnectVector /> </Styled> ); }; export default LostConnect;
jayce-incognito/leapxpert-test-fe
src/styles/colors.ts
export const COLORS = { transparent: 'transparent', orange: '#FF8E00', white: 'white', black: '#000000', black1: '#333335', black2: '#121212', black3: '#222223', black4: '#222222', blue: '#25CDD6', blue1: '#0A3A3C', blue2: '#01828A', blue3: '#ACE9EC', blue4: '#004AA9', blue5: '#5995F0', blue6: '#00407E', red: '#FE4D4D', green: '#34C759', pink: '#E5006D', dark1: '#101111', dark2: '#0D3A3C', dark3: '#014E52', dark4: '#0A3A3C', dark5: '#245153', dark6: '#4D7B7A', lightGrey1: '#8C9C9D', lightGrey2: '#B9C9CA', lightGrey3: '#9AB7B8', lightGrey4: '#D1DFE0', lightGrey5: '#E4EEEF', lightGrey6: '#F0F5F5', lightGrey7: '#F0F9F9', lightGrey8: '#4A5656', lightGrey9: '#657576', lightGrey10: '#F6F6F6', lightGrey11: '#EDEDED', lightGrey12: '#F3F3F3', lightGrey13: '#E6EEEF', lightGrey14: '#FAFAFA', lightGrey15: '#DCDDDD', lightGrey16: '#8A8A9E', lightGrey17: '#707070', lightGrey18: '#DCDCDD', lightGrey19: '#F4F4F4', lightGrey20: '#F7F7F7', lightGrey21: '#BCBCBC', lightGrey22: '#D2D2D2', newGrey: '#8A8A8E', toastBackgroundDefault: 'rgba(107, 141, 143, 0.8)', toastBackgroundError: 'rgba(255, 101, 47, 0.8)', toastBackgroundWarning: 'rgba(255, 241, 192, 0.8)', toastBackgroundSuccess: 'rgba(42, 171, 160, 0.8)', overlayBlack: 'rgba(6, 40, 41, 0.9)', overlayBlackDark: 'rgba(0, 0, 0, 0.8)', overlayBlackLight: 'rgba(0, 0, 0, 0.3)', errorMessage: '#ed4337', colorPrimary: '#33373A', colorBlue: '#5995F0', green2: '#64A121', green3: '#018775', colorOrange: '#FF9500', colorRed: '#FF3B30', mottoGrey: '#8c9c9d', colorGrey: '#F3F3F3', colorGreyBold: '#8A8A8E', colorGreyMedium: '#C4C4C6', colorGreyLight: '#D8D8D8', colorManateeGrey: '#959599', colorKeyGrey: '#CBCBCB', };
jayce-incognito/leapxpert-test-fe
src/i18n/interface.ts
<gh_stars>0 import { ISettingLanguage } from 'src/module/Setting'; export interface ILanguage { general: IGeneralLanguage; setting: ISettingLanguage; } export interface IGeneralLanguage { copied: string; copy: string; seeKey: string; lostNetwork: string; btnReload: string; loadingTx: string; btnRetry: string; switched: string; removed: string; keys: string; readyDesc: string; cameraReadyDesc: string; hasCameraDesc: string; scanQrCode: string; placeQrCode: string; success: string; masterKey: string; masterLess: string; keychainName: string; masterKeyName: string; privateKey: string; phrase: string; btnSetting: string; btnTrash: string; }
jayce-incognito/leapxpert-test-fe
src/styles/fontSize.ts
<filename>src/styles/fontSize.ts export const FONT_SIZES = { superSmall: 12, small: 13, regular: 15, medium: 18, superMedium: 20, large: 22, avgLarge: 30, veryLarge: 38, superLarge: 40, };
jayce-incognito/leapxpert-test-fe
src/module/Home/index.ts
<gh_stars>0 export { default } from './Home'; export * from './Home.actions'; export * from './Home.constant'; export * from './Home.interface'; export * from './Home.reducer'; export * from './Home.selector'; export * from './Home.route';
jayce-incognito/leapxpert-test-fe
src/components/Icons/Copy.tsx
import React, { useEffect, useRef } from 'react'; import styled from 'styled-components'; import copy from 'copy-to-clipboard'; import { useDispatch, useSelector } from 'react-redux'; import { actionRemoveTooltip, actionShowTooltip } from 'src/module/Tooltip'; import { IGeneralLanguage } from 'src/i18n'; import { translateByFieldSelector } from 'src/module/Setting'; interface IProps { text?: string; } const Styled = styled.button` width: 19px; height: 19px; `; const CopyVector = React.memo((props: any) => { return ( <svg width={19} height={19}> <path d="M16.088 18.874c1.828 0 2.75-.914 2.75-2.725V7.255c0-1.81-.922-2.725-2.75-2.725h-1.512V3.186c0-1.811-.923-2.725-2.75-2.725H3c-1.846 0-2.76.914-2.76 2.725v8.894c0 1.81.914 2.725 2.76 2.725h1.503v1.344c0 1.811.914 2.725 2.76 2.725h8.824zM4.504 13.39H3.019c-.88 0-1.363-.475-1.363-1.389V3.265c0-.914.484-1.389 1.363-1.389h8.78c.87 0 1.362.475 1.362 1.389V4.53H7.264c-1.846 0-2.76.906-2.76 2.725v6.135zm11.558 4.069h-8.78c-.87 0-1.363-.475-1.363-1.389V7.334c0-.914.492-1.389 1.362-1.389h8.78c.87 0 1.363.475 1.363 1.389v8.736c0 .914-.492 1.389-1.362 1.389z" fill="#000" fillRule="nonzero" {...props} /> </svg> ); }); const id = 'copy'; const Copy = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { const { text } = props; const iconRef: any = useRef(); const dispatch = useDispatch(); const translate: IGeneralLanguage = useSelector(translateByFieldSelector)('general'); const handleCopyText = () => { if (text) { copy(text); dispatch( actionShowTooltip({ text: translate.copied, ref: iconRef ? iconRef.current : null, }), ); } }; const handleHover = () => { dispatch( actionShowTooltip({ id, text: translate.copy, ref: iconRef ? iconRef.current : null, timeout: 0, }), ); }; const handleHoverOut = () => { dispatch(actionRemoveTooltip(id)); }; useEffect(() => { return () => { dispatch(actionRemoveTooltip(id)); }; }); return ( <Styled className="icon" onClick={handleCopyText} {...props} onMouseOver={handleHover} onMouseOut={handleHoverOut} > <div ref={iconRef}> <CopyVector /> </div> </Styled> ); }; export default Copy;
jayce-incognito/leapxpert-test-fe
src/App.enhance.tsx
import React, { FunctionComponent } from 'react'; import ErrorBoundary from 'src/components/ErrorBoundary'; import { Provider, useSelector } from 'react-redux'; import { configStore, IConfigStore } from 'src/redux'; import { PersistGate } from 'redux-persist/integration/react'; import { compose } from 'recompose'; import { Detector } from 'react-detect-offline'; import { themeSelector, translateByFieldSelector } from 'src/module/Setting'; import { IGeneralLanguage } from './i18n'; import { Styled } from './App.styled'; const { store, persistor }: IConfigStore = configStore(); const LostConnect = React.memo(() => { const translate: IGeneralLanguage = useSelector(translateByFieldSelector)('general'); const theme = useSelector(themeSelector); return ( <ErrorBoundary> <Styled theme={theme}> <div className="preload-container lost-network"> <p className="sub-text" dangerouslySetInnerHTML={{ __html: translate.lostNetwork }} /> </div> </Styled> </ErrorBoundary> ); }); const withNetwork = (WrappedComponent: React.FunctionComponent) => (props: any) => { return ( <ErrorBoundary> <Detector render={({ online }: { online: boolean }) => online ? <WrappedComponent {...props} /> : <LostConnect /> } /> </ErrorBoundary> ); }; const enhance = (WrappedComponent: FunctionComponent) => (props: any) => { return ( <ErrorBoundary> <Provider store={store}> <PersistGate loading={<div>...</div>} persistor={persistor}> {!!store && <WrappedComponent {...props} />} </PersistGate> </Provider> </ErrorBoundary> ); }; export default compose(enhance);
jayce-incognito/leapxpert-test-fe
src/components/Core/index.ts
<reponame>jayce-incognito/leapxpert-test-fe export * from './Checkbox'; export * from './Button'; export * from './ToggleSwitch'; export * from './Input'; export * from './TextArea'; export { default as TyniButton } from './TyniButton';
jayce-incognito/leapxpert-test-fe
src/components/Icons/Question.tsx
<reponame>jayce-incognito/leapxpert-test-fe import React from 'react'; import styled from 'styled-components'; interface IProps { width?: number; height?: number; } const Styled = styled.button<{ width?: number; height?: number }>` width: ${(props) => (props?.width ? `${props?.width}px` : `15px`)}; height: ${(props) => (props?.height ? `${props?.height}px` : `15px`)}; `; const QuestionVector = React.memo((props: any) => { return ( <svg width={15} height={15} viewBox="0 0 14 14"> <path d="M6.61 13.892c3.543 0 6.475-2.94 6.475-6.475 0-3.542-2.939-6.475-6.48-6.475C3.068.942.135 3.875.135 7.417c0 3.536 2.94 6.475 6.475 6.475zm-.139-5.117c-.336 0-.527-.177-.527-.52v-.083c0-.647.356-.99.826-1.32.57-.4.844-.616.844-1.06 0-.495-.387-.832-.978-.832-.438 0-.749.216-.965.572-.215.247-.273.444-.647.444a.448.448 0 01-.457-.45c0-.109.032-.223.063-.324.178-.603.914-1.13 2.044-1.13 1.118 0 2.089.577 2.089 1.67 0 .786-.457 1.167-1.092 1.586-.457.298-.667.533-.667.901v.077c0 .26-.203.47-.533.47zm-.013 1.95c-.38 0-.71-.306-.71-.68 0-.375.323-.686.71-.686.388 0 .711.305.711.686 0 .38-.33.68-.71.68z" fill="#FFF" fillRule="nonzero" {...props} /> </svg> ); }); const Question = (props: IProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => { return ( <Styled className="icon" {...props}> <QuestionVector /> </Styled> ); }; export default Question;
jayce-incognito/leapxpert-test-fe
src/module/Setting/features/Network/Network.tsx
import React from 'react'; import { useDispatch, useSelector } from 'react-redux'; import Header from 'src/components/Header'; import { actionSetServer, serverSelector } from 'src/module/Setting'; import { IServer, MAINNET_SERVER, TESTNET_SERVER } from 'src/services'; import styled from 'styled-components'; interface INetworkItem { title: string; desc: string; onChangeNetwork?: () => void; serverID: string; } const Styled = styled.div` cursor: pointer; .network-item { margin-bottom: 30px; } .network-item .title { margin-bottom: 15px; } .network-item .desc { } `; const NetworkItem = React.memo((props: INetworkItem) => { const { title, desc, onChangeNetwork, serverID } = props; const handleClick = () => typeof onChangeNetwork === 'function' && onChangeNetwork(); const server = useSelector(serverSelector); const actived = server.id === serverID; return ( <div className={`network-item ${actived ? 'main-text' : 'sub-text'}`} onClick={handleClick}> <p className="title fs-medium">{title}</p> <p className="desc fs-regular">{desc}</p> </div> ); }); const Network = React.memo(() => { const defaultServer = useSelector(serverSelector); const dispatch = useDispatch(); const handleChangeNetwork = async (server: IServer) => { if (defaultServer.id !== server.id && server.id !== 'local') { await dispatch(actionSetServer(server)); } }; return ( <Styled> <Header /> {[MAINNET_SERVER, TESTNET_SERVER].map((server) => ( <NetworkItem key={server.id} serverID={server.id} title={server.name} desc={server.address} onChangeNetwork={() => handleChangeNetwork(server)} /> ))} </Styled> ); }); export default Network;
jayce-incognito/leapxpert-test-fe
src/components/Core/FillCheckBox/index.ts
export { default } from './FillCheckBox';
jayce-incognito/leapxpert-test-fe
src/module/Setting/Setting.tsx
<gh_stars>0 import React from 'react'; import styled from 'styled-components'; import withSetting, { IMergeProps } from 'src/module/Setting/Setting.enhance'; import SettingItem, { ISettingItem } from './features/SettingItem'; const Styled = styled.div``; const Setting = (props: IMergeProps & any) => { const { settingFactories }: IMergeProps = props; return ( <Styled className="scroll-view"> {settingFactories.map((item: ISettingItem) => ( <SettingItem key={item.title} {...item} /> ))} </Styled> ); }; export default withSetting(React.memo(Setting));
jayce-incognito/leapxpert-test-fe
src/module/Setting/Setting.constant.ts
export const ACTION_FETCHED = `[setting] Fetched data`; export const ACTION_TOGGLE_HOME_CONFIGS = `[setting] Toggle home configs`; export const ACTION_TOGGLE_DECIMAL_DIGITS = '[setting] Toggle decimal digits'; export const ACTION_TOGGLE_DEV_MODE = '[setting] Toggle dev mode'; export const ACTION_TOGGLE_MODE_SAVE_BURN_TX = '[setting] Toggle mode save burn tx'; export const ACTION_TOGGLE_MODE_SAVE_RAW_BURN_TX = '[setting] Toggle mode save raw burn tx'; export const ACTION_TOGGLE_DARK_MODE = '[setting] Toggle dark mode ui'; export const ACTION_CHANGE_LANGUAGE = `[setting] Change language`; export const ACTION_SET_SERVER = `[setting] Set server`;
JuliusNarvilas/KingdomDeathHelperIonic
KingdomDeathHelper/src/app/tab1/tab1.page.ts
<reponame>JuliusNarvilas/KingdomDeathHelperIonic import { Component, OnInit } from '@angular/core'; import { File, Entry } from '@ionic-native/file/ngx'; import { Platform, AlertController, ToastController } from '@ionic/angular'; import { FileOpener } from '@ionic-native/file-opener/ngx'; import { Router, ActivatedRoute } from '@angular/router'; import { log } from 'util'; @Component({ selector: 'app-tab1', templateUrl: 'tab1.page.html', styleUrls: ['tab1.page.scss'] }) export class Tab1Page implements OnInit { directories = []; folder = ''; copyFile: Entry = null; shouldMove = false; constructor( private file: File, private plt: Platform, private alertCtrl: AlertController, private fileOpener: FileOpener, private router: Router, private route: ActivatedRoute, private toastCtrl: ToastController ) {} ngOnInit() { this.folder = this.route.snapshot.paramMap.get('folder') || ''; this.loadDocuments(); } loadDocuments() { this.plt.ready().then(() => { // Reset for later copy/move operations this.copyFile = null; this.shouldMove = false; log("INIT this.file.dataDirectory: " + this.file.dataDirectory); log("INIT this.file.documentsDirectory: " + this.file.documentsDirectory); this.file.listDir(this.file.dataDirectory, this.folder).then(res => { this.directories = res; }); }); } async createFolder() { let alert = await this.alertCtrl.create({ header: 'Create folder', message: 'Please specify the name of the new folder', inputs: [ { name: 'name', type: 'text', placeholder: 'MyDir' } ], buttons: [ { text: 'Cancel', role: 'cancel', cssClass: 'secondary' }, { text: 'Create', handler: data => { this.file .createDir( `${this.file.dataDirectory}/${this.folder}`, data.name, false ) .then(res => { this.loadDocuments(); }); } } ] }); await alert.present(); } async createFile() { let alert = await this.alertCtrl.create({ header: 'Create file', message: 'Please specify the name of the new file', inputs: [ { name: 'name', type: 'text', placeholder: 'MyFile' } ], buttons: [ { text: 'Cancel', role: 'cancel', cssClass: 'secondary' }, { text: 'Create', handler: data => { this.file .writeFile( `${this.file.dataDirectory}/${this.folder}`, `${data.name}.txt`, `My custom text - ${new Date().getTime()}` ) .then(res => { this.loadDocuments(); }); } } ] }); await alert.present(); } deleteFile(file: Entry) { let path = this.file.dataDirectory + this.folder; this.file.removeFile(path, file.name).then(() => { this.loadDocuments(); }); } startCopy(file: Entry, moveFile = false) { this.copyFile = file; this.shouldMove = moveFile; } async itemClicked(file: Entry) { log("TESTING: " + file.name); if (this.copyFile) { // Copy is in action! if (!file.isDirectory) { let toast = await this.toastCtrl.create({ message: 'Please select a folder for your operation' }); await toast.present(); return; } // Finish the ongoing operation this.finishCopyFile(file); } else { // Open the file or folder if (file.isFile) { this.fileOpener.open(file.nativeURL, 'text/plain'); } else { let pathToOpen = this.folder != '' ? this.folder + '/' + file.name : file.name; let folder = encodeURIComponent(pathToOpen); this.router.navigateByUrl(`/home/${folder}`); } } } finishCopyFile(file: Entry) { let path = this.file.dataDirectory + this.folder; let newPath = this.file.dataDirectory + this.folder + '/' + file.name; if (this.shouldMove) { if (this.copyFile.isDirectory) { this.file .moveDir(path, this.copyFile.name, newPath, this.copyFile.name) .then(() => { this.loadDocuments(); }); } else { this.file .moveFile(path, this.copyFile.name, newPath, this.copyFile.name) .then(() => { this.loadDocuments(); }); } } else { if (this.copyFile.isDirectory) { this.file .copyDir(path, this.copyFile.name, newPath, this.copyFile.name) .then(() => { this.loadDocuments(); }); } else { this.file .copyFile(path, this.copyFile.name, newPath, this.copyFile.name) .then(() => { this.loadDocuments(); }); } } } }
danschultz/enumerables
src/enumerate.ts
import Enumerable from "./enumerable"; export default function<T>(iterable: Iterable<T>): Enumerable<T> { return new Enumerable(iterable); }
danschultz/enumerables
src/filter_iterator.ts
import {Predicate} from "./predicate"; export default class FilterIterator<T> implements Iterator<T> { constructor(private iterator: Iterator<T>, private predicate: Predicate<T>) {} public next(): IteratorResult<T> { let next = this.iterator.next(); if (!next.done) { if (this.predicate(next.value)) { return next; } else { return this.next(); } } else { return {value: undefined, done: true}; } } }
danschultz/enumerables
src/flatten_iterator.ts
import {isIterable} from "./utils"; export default class FlattenIterator<T> implements Iterator<T> { private iterators: Iterator<T>[]; constructor(private iterator: Iterator<T>) { this.iterators = [iterator]; } public next(): IteratorResult<T> { if (this.iterators.length > 0) { let next = this.iterators[0].next(); if (next.done) { this.iterators.shift(); return this.next(); } else if (isIterable(next.value)) { this.iterators.unshift(next.value[Symbol.iterator]()); return this.next(); } else { return next; } } else { return {value: undefined, done: true}; } } }
danschultz/enumerables
src/range_iterator.ts
import Enumerable from "./enumerable"; class RangeIterator implements Iterator<number> { private nextValue: number; constructor(private start: number, private stop: number, private step: number) { if (step > 0) { this.nextValue = start; } else { throw new RangeError(`Step in range should be greater than 0, was ${step}`); } } public next(): IteratorResult<number> { if (this.nextValue < this.stop) { let value = this.nextValue; this.nextValue = value + this.step; return {value: value, done: false}; } else { return {value: undefined, done: true}; } } } export default function(start: number, stop: number, step = 1): Enumerable<number> { return new Enumerable({ [Symbol.iterator]() { return new RangeIterator(start, stop, step); } }) }
danschultz/enumerables
src/map_iterator.ts
<reponame>danschultz/enumerables export default class MapIterator<T, R> implements Iterator<R> { constructor(private iterator: Iterator<T>, private block: (value: T) => R) {} public next(): IteratorResult<R> { let next = this.iterator.next(); if (!next.done) { return {value: this.block(next.value), done: false}; } else { return {value: undefined, done: true}; } } }
danschultz/enumerables
src/skip_iterator.ts
export default class SkipIterator<T> implements Iterator<T> { constructor(private iterator: Iterator<T>, private count: number) { for (let i = 0; i < this.count; i++) { this.iterator.next(); } } public next(): IteratorResult<T> { return this.iterator.next(); } }
danschultz/enumerables
test/enumerable_test.ts
import {expect} from "chai"; import {enumerate, range} from "../src/main.ts"; describe("Enumerable", () => { describe("#every()", () => { it("returns true when all values satisfy predicate", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.every(n => n > 0)).to.be.true; }); it("returns false when one value doesn't satisfy predicate", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.every(n => n > 1)).to.be.false; }); }); describe("#some()", () => { it("returns true when one value satisfies predicate", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.some(n => n === 1)).to.be.true; }); it("returns false when no values satisfy predicate", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.some(n => n > 3)).to.be.false; }); }); describe("#filter()", () => { it("should only contain elements satisfying predicate", () => { let enumerable = enumerate([1, 2, 3, 4, 5]).filter(i => i % 2 === 0); let expected = [2, 4]; expect(enumerable.toArray()).to.eql(expected); }); }); describe("#flatten()", () => { it("should reduce an iterable of iterables into a flat iterable", () => { let enumerable = enumerate([1, [2, 3], [[4, 5], [[6]]], 7]).flatten(); let expected = [1, 2, 3, 4, 5, 6, 7]; expect(enumerable.toArray()).to.eql(expected); }); }); describe("#expand()", () => { it("returns an array of arrays", () => { let enumerable = enumerate([1, 2, 3]).expand(i => [i - 1, i]); let expected = [[0, 1], [1, 2], [2, 3]]; expect(enumerable.toArray()).to.eql(expected); }); }); describe("#forEach()", () => { it("should iterate through each value", () => { let expected = [1, 2, 3]; let actual = []; enumerate([1, 2, 3]).forEach(v => actual.push(v)); expect(actual).to.eql(expected); }) }); describe("#join()", () => { it("converts each element to a string and concatenates each string", () => { let enumerable = enumerate([1, 2, 3]); let expected = "1, 2, 3"; expect(enumerable.join(", ")).to.eql(expected); }); it("returns an empty string when enumerable is empty", () => { expect(enumerate([]).join(", ")).to.eql(""); }); }); describe("#map()", () => { it("should map each value", () => { let enumerable = enumerate([1, 2, 3]).map(value => value + 1); let expected = [2, 3, 4]; expect(enumerable.toArray()).to.eql(expected); }); }); describe("#reduce()", () => { context("with initial value", () => { it("uses initial value for accumulator", () => { let enumerable = enumerate([1, 2, 3]); let actual = enumerable.reduce((prev, element) => prev + element, 1); expect(actual).to.eql(7); }); }); context("without initial value", () => { it("uses first value for accumulator", () => { let enumerable = enumerate([1, 2, 3]); let actual = enumerable.reduce((prev, element) => prev + element); expect(actual).to.eql(6); }); }); }); describe("#take()", () => { context("when value less than length", () => { it("should return subset of elements", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.take(2).toArray()).to.eql([1, 2]); }); }); context("when value greater than length", () => { it("returns all elements", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.take(5).toArray()).to.eql([1, 2, 3]); }); }); }); describe("#toArray()", () => { it("should return an ordered array with each value", () => { let enumerable = enumerate([1, 2, 3]); let expected = [1, 2, 3]; expect(enumerable.toArray()).to.eql(expected); }); it("should return a new array for each call", () => { let enumerable = enumerate([1, 2, 3]); let result1 = enumerable.toArray(); let result2 = enumerable.toArray(); expect(result1.length).to.eql(3); expect(result2.length).to.eql(3); expect(result1).to.not.eq(result2); }); }); describe("#skip()", () => { context("when count is 0", () => { it("should return all elements", () => { let enumerable = enumerate([1, 2, 3, 4, 5]).skip(0); let expected = [1, 2, 3, 4, 5]; expect(enumerable.toArray()).to.eql(expected); }); }); context("when count is less than length", () => { it("should skip first N elements", () => { let enumerable = enumerate([1, 2, 3, 4, 5]).skip(2); let expected = [3, 4, 5]; expect(enumerable.toArray()).to.eql(expected); }); }); context("when count is equal to length", () => { it("should be empty", () => { let enumerable = enumerate([1, 2, 3]).skip(3); let expected = []; expect(enumerable.toArray()).to.eql(expected); }); }); context("when count is greater than length", () => { it("should be empty", () => { let enumerable = enumerate([1, 2, 3]).skip(4); let expected = []; expect(enumerable.toArray()).to.eql(expected); }); }); }); describe("#first", () => { it("should return the first element when not empty", () => { let enumerable = enumerate([1, 2]); expect(enumerable.first).to.eql(1); }); it("should return null when empty", () => { let enumerable = enumerate([]); expect(enumerable.first).to.be.null; }); }); describe("#last", () => { it("should return the last element when not empty", () => { let enumerable = enumerate([1, 2, 3]); expect(enumerable.last).to.eql(3); }); it("should return null when empty", () => { let enumerable = enumerate([]); expect(enumerable.first).to.be.null; }); }); describe("#length", () => { it("should return the number of elements", () => { expect(enumerate([1, 2, 3]).length).to.eql(3); }); }); describe("#isEmpty", () => { it("should return true when not empty", () => { let enumerable = enumerate([]); expect(enumerable.isEmpty).to.eql(true); }); it("should return false when not empty", () => { let enumerable = enumerate([1, 2]); expect(enumerable.isEmpty).to.eql(false); }); }); describe("#isNotEmpty", () => { it("should return false when not empty", () => { let enumerable = enumerate([1, 2]); expect(enumerable.isNotEmpty).to.eql(true); }); it("should return true when not empty", () => { let enumerable = enumerate([]); expect(enumerable.isNotEmpty).to.eql(false); }); }); }); describe("range()", () => { context("when step positive", () => { it("should iterate from start to end by step", () => { let nums = range(0, 5, 2).toArray(); expect(nums).to.eql([0, 2, 4]); }); }); context("when step non-positive", () => { it("should throw an error", () => { expect(() => range(0, 5, 0).toArray()).to.throw(RangeError); }); }); });
danschultz/enumerables
dist/main.d.ts
<gh_stars>0 // Generated by dts-bundle v0.5.0 declare module 'enumerables' { export { default as enumerate } from "enumerables/enumerate"; export { default as range } from "enumerables/range_iterator"; export { default as Enumerable } from "enumerables/enumerable"; } declare module 'enumerables/enumerate' { import Enumerable from "enumerables/enumerable"; export default function <T>(iterable: Iterable<T>): Enumerable<T>; } declare module 'enumerables/range_iterator' { import Enumerable from "enumerables/enumerable"; export default function (start: number, stop: number, step?: number): Enumerable<number>; } declare module 'enumerables/enumerable' { import { Predicate } from "enumerables/predicate"; export default class Enumerable<T> { constructor(iterable: Iterable<T>); [Symbol.iterator](): Iterator<T>; every(predicate: Predicate<T>): boolean; expand(expansion: (e: T) => T[]): Enumerable<T[]>; filter(predicate: Predicate<T>): Enumerable<T>; flatten(): Enumerable<T>; join(separator?: string): string; map<R>(block: (value: T) => R): Enumerable<R>; reduce(accumulator: (prev: T, element: T) => T, initialValue?: T): T | undefined; reduce<R>(accumulator: (prev: R, element: T) => R, initialValue: R): R; forEach(block: (value: T) => void): void; skip(count: number): Enumerable<T>; some(predicate: Predicate<T>): boolean; take(count: number): Enumerable<T>; toArray(): T[]; readonly first: T | null; readonly last: T | null; readonly length: number; readonly isEmpty: boolean; readonly isNotEmpty: boolean; protected iterator(): Iterator<T>; } } declare module 'enumerables/predicate' { export type Predicate<T> = (value: T) => boolean; }
danschultz/enumerables
src/take_iterator.ts
<reponame>danschultz/enumerables<filename>src/take_iterator.ts export default class TakeIterator<T> implements Iterator<T> { private index = 0; constructor(private iterator: Iterator<T>, private count: number) {} public next(): IteratorResult<T> { return this.index++ < this.count ? this.iterator.next() : {value: undefined, done: true}; } }
danschultz/enumerables
src/utils.ts
export function isIterable(value: any): value is Iterable<any> { return value[Symbol.iterator] !== undefined; }
danschultz/enumerables
src/main.ts
<gh_stars>0 export {default as enumerate} from "./enumerate"; export {default as range} from "./range_iterator"; export {default as Enumerable} from "./enumerable";
danschultz/enumerables
src/enumerable.ts
import FilterIterator from "./filter_iterator"; import MapIterator from "./map_iterator"; import {Predicate} from "./predicate"; import TakeIterator from "./take_iterator"; import SkipIterator from "./skip_iterator"; import FlattenIterator from "./flatten_iterator"; export default class Enumerable<T> { constructor(private iterable: Iterable<T>) {} [Symbol.iterator](): Iterator<T> { return this.iterable[Symbol.iterator](); } public every(predicate: Predicate<T>): boolean { let iterator = this.iterator(); while (true) { let next = iterator.next(); if (next.done) { return true; } else if (!predicate(next.value)) { return false; } } } public expand(expansion: (e: T) => T[]): Enumerable<T[]> { return new Enumerable(this.reduce((elements, element) => { elements.push(expansion(element)); return elements; }, [])); } public filter(predicate: Predicate<T>): Enumerable<T> { const iterator = this.iterator(); return new Enumerable({ [Symbol.iterator]() { return new FilterIterator(iterator, predicate); } }) } public flatten(): Enumerable<T> { let iterator = this.iterator(); return new Enumerable({ [Symbol.iterator]() { return new FlattenIterator(iterator); } }) } public join(separator = ""): string { let initialValue = (this.first || "").toString(); let skipped = this.skip(1); return skipped.reduce((str, element) => `${str}${separator}${element}`, initialValue); } public map<R>(block: (value: T) => R): Enumerable<R> { const iterator = this.iterator(); return new Enumerable<R>({ [Symbol.iterator]() { return new MapIterator(iterator, block); } }); } public reduce(accumulator: (prev: T, element: T) => T, initialValue?: T): T | undefined; public reduce<R>(accumulator: (prev: R, element: T) => R, initialValue: R): R; public reduce<R>(accumulator: (prev: R | T, element: T) => R, initialValue?: R): R | T | undefined { let iterator = this.iterator(); let accumulated = initialValue !== undefined ? initialValue : iterator.next().value; while (true) { let result = iterator.next(); if (result.done) { break; } else { accumulated = accumulator(accumulated, result.value); } } return accumulated; } public forEach(block: (value: T) => void): void { let iterator = this.iterator(); while (true) { let result = iterator.next(); if (result.done) { break; } else { block(result.value); } } } public skip(count: number): Enumerable<T> { let iterator = this.iterator(); return new Enumerable({ [Symbol.iterator]() { return new SkipIterator(iterator, count); } }); } public some(predicate: Predicate<T>): boolean { let iterator = this.iterator(); while (true) { let next = iterator.next(); if (next.done) { return false; } else if (predicate(next.value)) { return true; } } } public take(count: number): Enumerable<T> { let iterator = this.iterator(); return new Enumerable({ [Symbol.iterator]() { return new TakeIterator(iterator, count); } }); } public toArray(): T[] { return this.reduce((values, value) => { values.push(value); return values; }, []); } public get first(): T | null { return this.iterator().next().value || null; } public get last(): T | null { let iterator = this.iterator(); let last = null; while (true) { let next = iterator.next(); if (next.done) { return last; } else { last = next.value; } } } public get length(): number { return this.reduce((i, _) => i + 1, 0); } public get isEmpty(): boolean { return this.iterator().next().done; } public get isNotEmpty(): boolean { return !this.isEmpty; } protected iterator(): Iterator<T> { return this[Symbol.iterator](); } }
JazminFeliu/test-api-nest
src/test-api/test-api.controller.ts
<reponame>JazminFeliu/test-api-nest import { Controller, Get } from '@nestjs/common'; @Controller('test-api') export class TestApiController { @Get() getTestApi(){ return "Hola desde la api nest!"; } }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/flood-analysis/FloodAnalysis.ts
import { Viewer, Color, Cartesian3, Entity, Cartographic, CallbackProperty, } from 'cesium' import Draw from '../draw/Draw' import { DrawMode } from '../draw/Draw' export type DrawFloodAnalysisUserCallBackOption = { stoped?: () => void } export type FloodAnimateOption = { totalMilliseconds?: number totalFrame?: number currentHeightChange?: (val: number) => void } class FloodAnalysis extends Draw { private static FLOOD_ANALYSIS_DRAWED_POLYGON_NAME_ADDITION = '_FOR_FLOOD_ANALYSIS' public static FLOOD_ANALYSIS_MAX_HEIGHT_LIMIT = 10000 public static FLOOD_ANALYSIS_MIN_HEIGHT_LIMIT = 0 private _minHeight = 0 private _maxHeight = 9999 private intervalId = -1 get minHeight(): number { return this._minHeight } set minHeight(val: number) { if (val < FloodAnalysis.FLOOD_ANALYSIS_MIN_HEIGHT_LIMIT) { val = FloodAnalysis.FLOOD_ANALYSIS_MIN_HEIGHT_LIMIT } if (val > this.maxHeight) { val = this.maxHeight - 0.01 } this._minHeight = val } get maxHeight(): number { return this._maxHeight } set maxHeight(val: number) { if (val > FloodAnalysis.FLOOD_ANALYSIS_MAX_HEIGHT_LIMIT) { val = FloodAnalysis.FLOOD_ANALYSIS_MAX_HEIGHT_LIMIT } if (val < this.minHeight) { val = this.minHeight + 0.01 } this._maxHeight = val } constructor(viewer: Viewer) { super(viewer) } public drawFloodArea(option?: DrawFloodAnalysisUserCallBackOption): void { this.stopFloodAnimate() this.viewer.scene.globe.depthTestAgainstTerrain = true this.removeDrawedFloodArea() const self = this this.drawPolygon({ nameAddition: FloodAnalysis.FLOOD_ANALYSIS_DRAWED_POLYGON_NAME_ADDITION, color: Color.YELLOW, material: Color.fromCssColorString('#6191daa1'), stoped: () => { option && option.stoped && option.stoped() }, beforeStop: (ps) => self.calcFloodAreaMinMaxHeight(ps), }) } public removeDrawedFloodArea(): void { this.stopFloodAnimate() this.removeDrawedPolygon( FloodAnalysis.FLOOD_ANALYSIS_DRAWED_POLYGON_NAME_ADDITION ) } private currentFloodArea(): Entity | undefined { const { viewer, drawShapeEntityName } = this const entities = viewer.entities.values let index = 0 const entityName = drawShapeEntityName( DrawMode.Polygon, FloodAnalysis.FLOOD_ANALYSIS_DRAWED_POLYGON_NAME_ADDITION ) while (index < entities.length) { const model = entities[index] if (model.name === entityName) { return model } else { index++ } } return undefined } private calcFloodAreaMinMaxHeight(points: Cartesian3[]): void { if (!points) { return } // calculate from ellipsoid // const ellipsoid = this.viewer.scene.globe.ellipsoid // const calcHeight = (cartesian3: Cesium.Cartesian3) => { // return ( // viewer.scene.globe.getHeight( // ellipsoid.cartesianToCartographic(cartesian3) // ) || 0 // ) // } // calculate from pick position const calcHeight = (cartesian3: Cartesian3) => { return Cartographic.fromCartesian(cartesian3).height } let minH = calcHeight(points[0]) let maxH = minH const len = points.length for (let i = 1; i < len; i++) { const h = calcHeight(points[i]) if (h > maxH) { maxH = h } if (h < minH) { minH = h } } this.minHeight = minH this.maxHeight = maxH } public setCurrentHeight(val: number, isConstant: boolean = true): void { const floodArea = this.currentFloodArea() if (!floodArea || !floodArea.polygon) { return } this.stopFloodAnimate() floodArea.polygon.extrudedHeight = new CallbackProperty(() => { return val }, isConstant) } public startFloodAnimate(option?: FloodAnimateOption): void { this.stopFloodAnimate() const floodArea = this.currentFloodArea() if (!floodArea) { return } const { currentHeightChange } = option || {} let { totalMilliseconds = 3000, totalFrame = 60 } = option || {} if (totalMilliseconds < 300) { totalMilliseconds = 300 } if (totalMilliseconds / totalFrame < 10) { totalFrame = totalMilliseconds / 10 } const { maxHeight, minHeight } = this const timespan = totalMilliseconds / totalFrame // timespan per frame const heightDiff = maxHeight - minHeight const heightGrow = heightDiff / totalFrame let index = 0 const self = this this.intervalId = window.setInterval(() => { if (!floodArea || !floodArea.polygon) { return } const currentHeight = minHeight + heightGrow * index floodArea.polygon.extrudedHeight = new CallbackProperty(() => { return currentHeight }, false) currentHeightChange && currentHeightChange(currentHeight) index++ // const nowH = floodArea.polygon.extrudedHeight.getValue( // self.viewer.clock.currentTime // ) if (currentHeight > maxHeight) { self.stopFloodAnimate() } }, timespan) } public stopFloodAnimate(): void { clearInterval(this.intervalId) } } export default FloodAnalysis
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/action-types.ts
export enum DrawActionTypes { RESET_STATE = 'RESET_STATE', // draw SET_DRAW_POINT_ACTIVE = 'SET_DRAW_POINT_ACTIVE', SET_DRAW_POLYLINE_ACTIVE = 'SET_DRAW_POLYLINE_ACTIVE', SET_DRAW_POLYGON_ACTIVE = 'SET_DRAW_POLYGON_ACTIVE', }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/scene-mode/index.ts
<reponame>CN-3211/vt-cesium2.0<gh_stars>0 import { Viewer, SceneMode } from 'cesium' export default function (viewer: Viewer, mode: SceneMode, duration?: number) { switch (mode) { case SceneMode.SCENE2D: viewer.scene.morphTo2D(duration) break case SceneMode.SCENE3D: viewer.scene.morphTo3D(duration) break case SceneMode.COLUMBUS_VIEW: viewer.scene.morphToColumbusView(duration) break default: break } }
CN-3211/vt-cesium2.0
src/@types/shims-window-cesium.d.ts
/* * @Date: 2022-03-28 09:56:52 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-29 14:43:24 * @FilePath: /vue3-cesium-typescript-start-up-template/src/@types/shims-window-cesium.d.ts */ /* eslint-disable */ declare namespace globalThis { import('cesium') import * as Cesium from 'cesium' interface Window { viewer?: Cesium.Viewer Cesium?: Cesium } }
CN-3211/vt-cesium2.0
src/libs/cesium/cesium-jt.ts
<gh_stars>0 import * as Cesium from 'cesium' import Draw from '@/libs/cesium/libs/draw/Draw' import Measure from '@/libs/cesium/libs/measure/Measure' import ElevationContour from '@/libs/cesium/libs/elevation-contour/ElevationContour' import FlyTo from '@/libs/cesium/libs/fly-to/FlyTo' import Highlight from '@/libs/cesium/libs/highlight/Highlight' import Light from '@/libs/cesium/libs/light/Light' import TerrainSampling from '@/libs/cesium/libs/terrain-sampling/TerrainSampling' import Classification from '@/libs/cesium/libs/classification/Classification' import PercentageChange from '@/libs/cesium/libs/percentage-change/PercentageChange' import FloodAnalysis from '@/libs/cesium/libs/flood-analysis/FloodAnalysis' import ImageryManager from '@/libs/cesium/libs/imagery-manager/ImageryManager' import PrimitiveManager from '@/libs/cesium/libs/primitive-manager/PrimitiveManager' import ClippingPlane from '@/libs/cesium/libs/clipping-plane/ClippingPlane' import Viewshed from '@/libs/cesium/libs/viewshed/Viewshed' import type { Option } from '@/libs/cesium/libs/viewshed/Viewshed' class Jt { protected viewer: Cesium.Viewer constructor(viewer: Cesium.Viewer) { this.viewer = viewer } private _draw?: Draw public get draw(): Draw { if (!this._draw) { this._draw = new Draw(this.viewer) } return this._draw } private _elevationContour?: ElevationContour public get elevationContour(): ElevationContour { if (!this._elevationContour) { this._elevationContour = new ElevationContour(this.viewer) } return this._elevationContour } private _flyTo?: FlyTo public get flyTo(): FlyTo { if (!this._flyTo) { this._flyTo = new FlyTo(this.viewer) } return this._flyTo } private _highlight?: Highlight public get highlight(): Highlight { if (!this._highlight) { this._highlight = new Highlight(this.viewer) } return this._highlight } private _light?: Light public get light(): Light { if (!this._light) { this._light = new Light(this.viewer) } return this._light } private _terrainSampling?: TerrainSampling public get terrainSampling(): TerrainSampling { if (!this._terrainSampling) { this._terrainSampling = new TerrainSampling(this.viewer) } return this._terrainSampling } private _classification?: Classification public get classification(): Classification { if (!this._classification) { this._classification = new Classification(this.viewer) } return this._classification } private _percentageChange?: PercentageChange public get percentageChange(): PercentageChange { if (!this._percentageChange) { this._percentageChange = new PercentageChange(this.viewer) } return this._percentageChange } private _measure?: Measure public get measure(): Measure { if (!this._measure) { this._measure = new Measure(this.viewer) } return this._measure } private _floodAnalysis?: FloodAnalysis public get floodAnalysis(): FloodAnalysis { if (!this._floodAnalysis) { this._floodAnalysis = new FloodAnalysis(this.viewer) } return this._floodAnalysis } private _imageryManager?: ImageryManager public get imageryManager(): ImageryManager { if (!this._imageryManager) { this._imageryManager = new ImageryManager(this.viewer) } return this._imageryManager } private _primitiveManager?: PrimitiveManager public get primitiveManager(): PrimitiveManager { if (!this._primitiveManager) { this._primitiveManager = new PrimitiveManager(this.viewer) } return this._primitiveManager } private _clippingPlane?: ClippingPlane public get clippingPlane(): ClippingPlane { if (!this._clippingPlane) { this._clippingPlane = new ClippingPlane(this.viewer) } return this._clippingPlane } private _viewshed?: Viewshed public get viewshed(): Viewshed { if (!this._viewshed) { this._viewshed = new Viewshed(this.viewer) } return this._viewshed } } export default Jt
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/effect/groups/nature/index.ts
<reponame>CN-3211/vt-cesium2.0 import { Group, ClickHandlerOption, OnMountedOption, ActiveOption, } from '../../../Types' import { NatureActionTypes } from '@/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/action-types' const view: Group = { name: '自然环境', items: [ { name: '太阳', icon: 'sun', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/nature/${NatureActionTypes.SWITCH_SHOW_SUN}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.nature.showSun, onMounted: (option: OnMountedOption): void => { option.store.state.jtCesiumVue.toolbar.nature.showSun = !!option?.viewer?.scene.sun?.show }, }, { name: '月亮', icon: 'moon', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/nature/${NatureActionTypes.SWITCH_SHOW_MOON}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.nature.showMoon, onMounted: (option: OnMountedOption): void => { option.store.state.jtCesiumVue.toolbar.nature.showMoon = !!option?.viewer?.scene.moon?.show }, }, { name: '大气层', icon: 'atmosphere', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/nature/${NatureActionTypes.SWITCH_SHOW_SKY_ATMOSPHERE}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.nature.showSkyAtmosphere, onMounted: (option: OnMountedOption): void => { option.store.state.jtCesiumVue.toolbar.nature.showSkyAtmosphere = !!option?.viewer?.scene.skyAtmosphere?.show }, }, { name: '日照', icon: 'shadow2', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/nature/${NatureActionTypes.SWITCH_ENABLE_LIGHT}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.nature.enableLighting, onMounted: (option: OnMountedOption): void => { if (option) { const { viewer } = option option.store.state.jtCesiumVue.toolbar.nature.enableLighting = !!viewer?.scene.globe?.enableLighting } }, dropdown: { componentName: 'earth-light-setting', }, }, { name: '天空盒', icon: 'universe', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/nature/${NatureActionTypes.SWITCH_SHOW_SKY_BOX}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.nature.showSkyBox, onMounted: (option: OnMountedOption): void => { option.store.state.jtCesiumVue.toolbar.nature.showSkyBox = !!option?.viewer?.scene.skyBox?.show }, }, { name: '阴影', icon: 'shadow3', disable: false, clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/toolbar/nature/${NatureActionTypes.SWITCH_SHOW_SHADOW}`, option ) }, active: (option: ActiveOption) => option.store.state.jtCesiumVue.toolbar.nature.showShadow, onMounted: (option: OnMountedOption): void => { option.store.state.jtCesiumVue.toolbar.nature.showShadow = !!option?.viewer?.shadows }, }, ], } export default view
CN-3211/vt-cesium2.0
src/store/modules/template/state.ts
<reponame>CN-3211/vt-cesium2.0 export type State = { test: boolean } export const defaultState = (): State => { return { test: false, } } export const state: State = defaultState()
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/actions.ts
import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { MeasureState } from './state' import { MeasureMutationTypes } from './mutation-types' import { MeasureActionTypes } from './action-types' export const actions: ActionTree<MeasureState, RootState> = { async [MeasureActionTypes.RESET_STATE]({ commit }) { commit(MeasureMutationTypes.RESET_STATE) }, // measure async [MeasureActionTypes.SET_MEASURE_POINT_ACTIVE]( { commit }, payload: boolean ) { commit(MeasureMutationTypes.SET_MEASURE_POINT_ACTIVE, payload) }, async [MeasureActionTypes.SET_MEASURE_POLYLINE_ACTIVE]( { commit }, payload: boolean ) { commit(MeasureMutationTypes.SET_MEASURE_POLYLINE_ACTIVE, payload) }, async [MeasureActionTypes.SET_MEASURE_POLYGON_ACTIVE]( { commit }, payload: boolean ) { commit(MeasureMutationTypes.SET_MEASURE_POLYGON_ACTIVE, payload) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/layout/mutations.ts
<reponame>CN-3211/vt-cesium2.0 import { MutationTree } from 'vuex' import { defaultState } from './state' import type { State } from './state' import type { OverlayDynamicView } from './state' import { LayoutHandlerEnum } from './enum-constant' import { uuid } from '@/utils' export const mutations: MutationTree<State> = { [LayoutHandlerEnum.RESET_STATE](state: State) { Object.assign(state, defaultState()) }, [LayoutHandlerEnum.SET_SHOW_BROWSER_PANEL](state: State, payload: boolean) { state.showBrowserPanel = payload }, [LayoutHandlerEnum.SET_SHOW_TOOLBAR](state: State, payload: boolean) { state.showToolbar = payload }, [LayoutHandlerEnum.SET_SHOW_SETTING_BUTTON](state: State, payload: boolean) { state.showSettingButton = payload }, [LayoutHandlerEnum.SET_TOOLBAR_HEIGHT](state: State, payload: number) { state.toolbarHeight = payload }, [LayoutHandlerEnum.ADD_UNIQUE_NAME_OVERLAY_DYNAMIC_VIEW_BY_NAME]( state: State, payload: string ) { if (!payload) { return } if (state.overlayDynamicViews.find((x) => x.name === payload)) { return } state.overlayDynamicViews.push({ name: payload, uuid: uuid(), }) }, [LayoutHandlerEnum.REMOVE_OVERLAY_DYNAMIC_VIEW_BY_NAME]( state: State, payload: string ) { state.overlayDynamicViews = state.overlayDynamicViews.filter( (x) => x.name !== payload ) }, }
CN-3211/vt-cesium2.0
src/store/index.ts
/* * @Date: 2022-03-30 14:29:50 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-31 14:36:48 * @FilePath: /vt-cesium2.0/src/store/index.ts */ import { InjectionKey } from 'vue' import { createStore, useStore as baseUseStore, Store } from 'vuex' import { store as template, State as TemplateState } from './modules/template' import { store as jtCesiumVue, BDCesiumVueState } from './modules/jt-cesium-vue' export type RootState = { template: TemplateState jtCesiumVue: BDCesiumVueState } /** * @description: 传入key作为标志符,唯一化当前useStore */ export const key: InjectionKey<Store<RootState>> = Symbol() export function useStore(): Store<RootState> { return baseUseStore(key) } export const store = createStore<RootState>({ modules: { template, // template for jtCesiumVue 方便理解 jtCesiumVue } }) export default store
CN-3211/vt-cesium2.0
src/components/viewer/defaultViewerProps.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/components/viewer/defaultViewerProps.ts /* * @Date: 2021-06-17 18:31:36 * @LastEditors: huangzh873 * @LastEditTime: 2021-11-26 08:53:11 * @FilePath: \cesium-web-vue\src\components\viewer\defaultViewerProps.ts */ import { PropType } from 'vue'; import { ClockViewModel, ProviderViewModel, ImageryProvider, TerrainProvider, SkyBox, SkyAtmosphere, MapProjection, Globe, DataSourceCollection } from 'cesium'; export default { id: { type: String, default: "cesiumContainer" }, geocoder: { type: Boolean, default: false }, cesiumPath: String, animation: { type: Boolean, default: false }, baseLayerPicker: { type: Boolean, default: false }, fullscreenButton: { type: Boolean, default: false }, vrButton: { type: Boolean, default: false }, homeButton: { type: Boolean, default: false }, infoBox: { type: Boolean, default: true }, sceneModePicker: { type: Boolean, default: false }, selectionIndicator: { type: Boolean, default: true }, timeline: { type: Boolean, default: false }, navigationHelpButton: { type: Boolean, default: false }, navigationInstructionsInitiallyVisible: { type: Boolean, default: false }, scene3DOnly: { type: Boolean, default: false }, shouldAnimate: { type: Boolean, default: false }, clockViewModel: Object as PropType<ClockViewModel>, selectedImageryProviderViewModel: Object as PropType<ProviderViewModel>, imageryProviderViewModels: Array as PropType<Array<ProviderViewModel>>, selectedTerrainProviderViewModel: Object as PropType<ProviderViewModel>, terrainProviderViewModels: Array as PropType<Array<ProviderViewModel>>, imageryProvider: Object as PropType<ImageryProvider>, terrainProvider: Object as PropType<TerrainProvider>, skyBox: Object as PropType<SkyBox>, skyAtmosphere: Object as PropType<SkyAtmosphere>, fullscreenElement: { type: [String, Element] as PropType<string | Element> }, useDefaultRenderLoop: { type: Boolean, default: true }, targetFrameRate: Number, showRenderLoopErrors: { type: Boolean, default: true }, useBrowserRecommendedResolution: { type: Boolean, default: true }, automaticallyTrackDataSourceClocks: { type: Boolean, default: true }, contextOptions: Object, sceneMode: { type: Number, default: 3 }, mapProjection: Object as PropType<MapProjection>, globe: Object as PropType<Globe>, orderIndependentTranslucency: { type: Boolean, default: true }, creditContainer: String, creditViewport: String, dataSources: Object as PropType<DataSourceCollection>, terrainExaggeration: { type: Number, default: 1.0 }, shadows: { type: Boolean, default: false }, terrainShadows: { type: Number, default: 3 }, mapMode2D: { type: Number, default: 1 }, projectionPicker: { type: Boolean, default: false }, requestRenderMode: { type: Boolean, default: false }, maximumRenderTimeChange: { type: Number, default: 0.0 }, debugShowFramesPerSecond: { type: Boolean, default: false }, showCredit: { type: Boolean, default: false }, accessToken: String, navigation: { // for supermap type: Boolean, default: false }, TZCode: { type: String, default: new Date().getTimezoneOffset() === 0 ? 'UTC' : 'UTC' + '+' + -(new Date().getTimezoneOffset() / 60) }, UTCOffset: { type: Number, default: -new Date().getTimezoneOffset() }, removeCesiumScript: { type: Boolean, default: true }, autoSortImageryLayers: { type: Boolean, default: true }, enableMouseEvent: { type: Boolean, default: true }, skeleton: { type: [Boolean, Object], default: { dark: false, animation: 'wave', square: true, bordered: true, color: undefined } } }
CN-3211/vt-cesium2.0
src/libs/utils/debounce.ts
/* * @Date: 2022-03-30 16:45:49 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 16:46:27 * @FilePath: /vt-cesium2.0/src/libs/utils/debounce.ts */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const debounce = (fn: any, delay: number) => { let timer: any = -1 function debounced() { clearTimeout(timer) timer = setTimeout(function () { fn() }, delay) } return debounced } export default debounce
CN-3211/vt-cesium2.0
src/components/toolbarGroup/analysis/sectionAnalysis.ts
<filename>src/components/toolbarGroup/analysis/sectionAnalysis.ts /* * @Date: 2021-11-05 20:44:03 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-28 19:48:46 * @FilePath: /cesium-web-vue/src/components/toolbarGroup/analysis/sectionAnalysis.ts */ import * as echarts from 'echarts/core'; import { GridComponent, ToolboxComponent, TooltipComponent, DatasetComponent, } from 'echarts/components'; import { LineChart } from 'echarts/charts'; import { UniversalTransition } from 'echarts/features'; import { CanvasRenderer } from 'echarts/renderers'; import { DrawPolyline, polylineOptions } from '@/utils/vue-utils/draw/drawUtils'; import { CESIUM_3D_TILE, TERRAIN } from '@/constant/index'; import { Math as CMath, HeightReference, Viewer, Cartesian3, sampleTerrainMostDetailed, Cartographic, createWorldTerrain, EllipsoidGeodesic, Entity, VerticalOrigin, NearFarScalar, ConstantPositionProperty } from 'cesium'; echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition, ToolboxComponent, TooltipComponent, DatasetComponent]); class sectionAnalysis { viewer: Viewer; DrawPolylineIns: DrawPolyline; firstPoint: Cartesian3 = new Cartesian3(); start: Cartesian3 = new Cartesian3(); end: Cartesian3 = new Cartesian3(); echartDataGroup: { distance: number, height: number, lng: number, lat: number }[] = [] echartOptions: any = {} echartIns: echarts.ECharts | undefined = undefined tipGraphic: Entity | undefined = undefined drawType = TERRAIN constructor(viewer: Viewer, options?: polylineOptions) { this.viewer = viewer; this.DrawPolylineIns = new DrawPolyline(viewer, options); options && this.initOptions(options) this.echartOptions = { tooltip: { trigger: 'axis', textStyle: { align: 'left', }, position: function (pt) { return [pt[0], '10%']; }, formatter: (params) => { let inhtml = ""; if (params.length === 0) { // hideTipMarker(); return inhtml; } const height = params[0].value.height; // 海拔高度 const lng = params[0].value.lng; // 所在经纬度 const lat = params[0].value.lat; // 所在经纬度 const len = params[0].value.distance; // 距起点 // const hbgdStr = haoutil.str.formatLength(Number(params[0].value)); inhtml = `当前位置<br /> 距起点:${len.toFixed(2)}米<br /> 海拔:<span style='color:${params[0].color};'>${height.toFixed(2)}米</span><br /> 经度:${lng.toFixed(2)}<br /> 纬度:${lat.toFixed(2)}`; this.showTipMarker(height, lng, lat, inhtml); return inhtml; }, }, dataset: { source: this.echartDataGroup, }, xAxis: { type: 'category', boundaryGap: false, axisLabel: { color: "#FFF", // formatter: '{value}米' formatter: (value) => { const value2 = Math.round(value*100) return value2/100 + '米' } }, axisLine: { lineStyle: { color: "#ccc" } }, splitLine: { show: true, lineStyle: { color: "#ccc" } } }, yAxis: { axisLabel: { color: "#FFF", formatter: "{value} 米" }, }, grid: { width: 'auto', height: 'auto', left: '3%', right: '3%', top: '20%', bottom: '0%', containLabel: true, show: true }, series: [ { type: 'line', showSymbol: false, lineStyle: { color: '#ff4683' }, areaStyle: { opacity: 0.8, color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: 'rgb(255, 158, 68)' }, { offset: 1, color: 'rgb(255, 70, 131)' } ]) } } ] }; } initOptions(options: polylineOptions) { Object.keys(options).forEach(item => { this[item] = options[item]; }) } /** * @description: 鼠标触发tooltip和地图的交互,在地图上增加marker * @param {*} point * @param {*} z * @param {*} inthtml * @return { void } */ showTipMarker(height, lng, lat, inhtml): void { // 标记Marker的地点 const drawPosition = Cartesian3.fromDegrees(lng, lat, height); if (!this.tipGraphic) { this.tipGraphic = this.viewer.entities.add({ name: "当前点", position: drawPosition, billboard: { image: 'image/map-marker.png', scale: 0.2, heightReference: this.drawType === TERRAIN ? HeightReference.CLAMP_TO_GROUND : HeightReference.NONE, verticalOrigin: VerticalOrigin.BOTTOM, scaleByDistance: new NearFarScalar(10000, 1.0, 500000, 0.2) } }) // this.tipGraphic._setPositionsToCallback(); } if(drawPosition) { this.tipGraphic.position = new ConstantPositionProperty(drawPosition); } // this.tipGraphic.bindPopup(inthtml).openPopup(); } /** * @description: 借助DrawPolyline的方法来在地形上绘制剖面 * @param {*} * @return {*} */ drawSectionsOnMap() { let sampleIndex = 0; this.DrawPolylineIns.startCreate( positions => { if (sampleIndex) { this.start = positions[sampleIndex - 1]; this.end = positions[sampleIndex]; this.getSampledData() } else { // 每次开始新的绘制时,要把数据清空 this.echartDataGroup = []; this.firstPoint = positions[sampleIndex]; } sampleIndex++; }, () => { // 下次点击还可以画线但是需要把index重置为0 sampleIndex = 0; // 创建echart的div if(!this.echartIns) { this.echartIns = this.createEchartContainer(); } } ); } /** * @description: 两点之间采样100个点,在每次右键点击时掉用该方法,异步获取和更新数据,避免效率过低 * @param {*} * @return {*} */ getSampledData() { const sampledPositions = [Cartographic.fromCartesian(this.start)]; // 用于配置在3dtiles上采样 const sampledPositions_3dtiles = [this.start] const COUNT = 100; for (let i = 1; i < COUNT; i++) { const cart = Cartesian3.lerp(this.start, this.end, i / COUNT, new Cartesian3()); sampledPositions.push(Cartographic.fromCartesian(cart)); sampledPositions_3dtiles.push(cart); } sampledPositions.push(Cartographic.fromCartesian(this.end)); sampledPositions_3dtiles.push(this.end); /* 这里要改,代码太臃肿了 */ if(this.drawType === CESIUM_3D_TILE) { this.viewer.scene.clampToHeightMostDetailed(sampledPositions_3dtiles).then((res) => { const dataGroup = res.map(_item => { const item = Cartographic.fromCartesian(_item) const geodesic = new EllipsoidGeodesic(); geodesic.setEndPoints(Cartographic.fromCartesian(this.firstPoint), item); const distance = geodesic.surfaceDistance; return { distance: distance, height: item.height, lng: CMath.toDegrees(item.longitude), lat: CMath.toDegrees(item.latitude) } }) this.echartDataGroup = this.echartDataGroup.concat(dataGroup) // 异步获取和更新数据 if (this.echartOptions.dataset) { this.echartOptions.dataset.source = this.echartDataGroup } this.echartIns && this.echartIns.setOption(this.echartOptions) }) } else { sampleTerrainMostDetailed(createWorldTerrain(), sampledPositions).then((res) => { const dataGroup = res.map(item => { const geodesic = new EllipsoidGeodesic(); geodesic.setEndPoints(Cartographic.fromCartesian(this.firstPoint), item); const distance = geodesic.surfaceDistance; return { distance: distance, height: item.height, lng: CMath.toDegrees(item.longitude), lat: CMath.toDegrees(item.latitude) } }) this.echartDataGroup = this.echartDataGroup.concat(dataGroup) // 异步获取和更新数据 if (this.echartOptions.dataset) { this.echartOptions.dataset.source = this.echartDataGroup } this.echartIns && this.echartIns.setOption(this.echartOptions) }) } } /** * @description: 创建echart的div并挂载至最外层的index.vue文件下,div样式也是写在该文件中 * @param {*} * @return {echarts.ECharts} myChart */ createEchartContainer(): echarts.ECharts { const chart_panel = document.createElement('div'); const chart_container = document.createElement('div'); const indexDom = document.getElementById('mapContainer'); if (!indexDom) { throw new Error("echart初始化失败") } chart_panel.setAttribute('class', 'chart_panel') chart_container.setAttribute('class', 'chart_container') indexDom.appendChild(chart_panel); chart_panel.appendChild(chart_container) const myChart = echarts.init(chart_container); myChart.setOption(this.echartOptions) return myChart } stopDrawing() { const echartDiv = document.getElementsByClassName('chart_panel')[0]; if(echartDiv) { echartDiv.parentNode?.removeChild(echartDiv); } if(this.tipGraphic) { this.viewer.entities.remove(this.tipGraphic); } this.DrawPolylineIns.polylineGroup.forEach(item => { this.viewer.entities.remove(item); }) this.DrawPolylineIns.stopDrawing(); } } export { sectionAnalysis }
CN-3211/vt-cesium2.0
src/utils/index.ts
/* * @Date: 2021-11-04 21:29:17 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 14:48:08 * @FilePath: /vt-cesium2.0/src/utils/index.ts */ const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') const uuid = function (): string { const uuid:any[] = [] uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' let r for (let i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | (Math.random() * 16) uuid[i] = CHARS[i === 19 ? (r & 0x3) | 0x8 : r] } } return uuid.join('') } /** * @description: 节流函数,防止短时间内函数多次调用 * @param {function} fn - 需要节流的函数 * @param {number} wait - 设置wait时间内函数没有触发,则调用函数 * @return {*} */ function throttle(fn: (...args: any[]) => any, wait: number) { let timer:unknown; return function(movement: any) { const context = this; if(!timer) { timer = setTimeout(() => { fn.apply(context, [movement]); timer = null }, wait); } } } /** * @description: Proxy 代理模式深度监听对象、数组变化 * @param {*} obj - 需要监听的对象或者数组 * @param {*} callback - 变化后触发的回调函数 * @return {*} - proxy对象 */ function deepWatcher(obj: any, callback: any) { if(typeof obj === 'object') { for(const key in obj) { if(typeof obj[key] === 'object') { obj[key] = deepWatcher(obj[key], callback); } } } return new Proxy(obj, { set: function(target, key, value, receiver) { if(typeof value === 'object') { value = deepWatcher(value, callback); } const callbackType = target[key] === undefined ? 'create' : 'modify'; // 避免target是数组的情况下,因修改数组时length的变化触发回调 if (!(Array.isArray(target) && key === 'length')) { callback(callbackType, { target, key, value }); } return Reflect.set(target, key, value, receiver); } }) } export { uuid, throttle, deepWatcher }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/index.ts
import { Module } from 'vuex' import { RootState } from '@/store' import { store as jtPrimitive } from './modules/jt-primitive' import { state } from './state' import type { CesiumDataStateAndModule, State } from './state' export { CesiumDataStateAndModule } import { getters } from './getters' import { mutations } from './mutations' import { actions } from './actions' type CesiumDataState = CesiumDataStateAndModule | State export const store: Module<CesiumDataState, RootState> = { namespaced: true, state, getters, mutations, actions, modules: { jtPrimitive, }, }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/fly-to/FlyTo.ts
<reponame>CN-3211/vt-cesium2.0 import { Viewer, Matrix4, Cartesian3, Math, Rectangle, Camera, EasingFunction, } from 'cesium' class FlyTo { private viewer: Viewer constructor(viewer: Viewer) { this.viewer = viewer } flyTo(options: { destination: Cartesian3 | Rectangle orientation?: any duration?: number complete?: Camera.FlightCompleteCallback cancel?: Camera.FlightCancelledCallback endTransform?: Matrix4 maximumHeight?: number pitchAdjustHeight?: number flyOverLongitude?: number flyOverLongitudeWeight?: number convert?: boolean easingFunction?: EasingFunction.Callback }): void { this.viewer.camera.flyTo(options) } flyToEarth(): void { this.flyTo({ destination: Cartesian3.fromDegrees(110, 16, 20000000), orientation: { heading: Math.toRadians(0), pitch: Math.toRadians(-90), roll: 0.0, }, duration: 1, }) } flyToChina(): void { this.flyTo({ destination: Cartesian3.fromDegrees(109, 33.2, 5000000), orientation: { heading: Math.toRadians(0), pitch: Math.toRadians(-90), roll: 0.0, }, duration: 1, }) } } export default FlyTo
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/tool/groups/model/index.ts
<filename>src/components/jt-toolbar/config/contents/tool/groups/model/index.ts /* * @Date: 2022-04-06 16:45:35 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-06 16:51:03 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/tool/groups/model/index.ts */ import { Group, ClickHandlerOption } from '../../../Types' import { LayoutHandlerEnum } from '@/store/modules/jt-cesium-vue/modules/layout/enum-constant' const view: Group = { name: '模型', items: [ { name: '剖分', icon: 'overlap', clickHandler: (option: ClickHandlerOption): void => { option.store.dispatch( `jtCesiumVue/layout/${LayoutHandlerEnum.ADD_UNIQUE_NAME_OVERLAY_DYNAMIC_VIEW_BY_NAME}`, 'jt-primitive-clipping-plane' ) }, }, ], } export default view
CN-3211/vt-cesium2.0
src/router/index.ts
/* * @Date: 2022-03-29 16:52:36 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-29 17:17:56 * @FilePath: /vt-cesium2.0/src/router/index.ts */ import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router' import Index from '../views/index.vue' const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'home', component: Index } ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/mutations.ts
<gh_stars>0 import { MutationTree } from 'vuex' import { defaultState } from './state' import type { DrawState } from './state' import { DrawMutationTypes } from './mutation-types' export const mutations: MutationTree<DrawState> = { [DrawMutationTypes.RESET_STATE](state: DrawState) { Object.assign(state, defaultState()) }, // draw [DrawMutationTypes.SET_DRAW_POINT_ACTIVE]( state: DrawState, payload: boolean ) { state.drawPointActive = payload }, [DrawMutationTypes.SET_DRAW_POLYLINE_ACTIVE]( state: DrawState, payload: boolean ) { state.drawPolylineActive = payload }, [DrawMutationTypes.SET_DRAW_POLYGON_ACTIVE]( state: DrawState, payload: boolean ) { state.drawPolygonActive = payload }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/getters.ts
<reponame>CN-3211/vt-cesium2.0 import { GetterTree } from 'vuex' import { RootState } from '@/store' import { MeasureState } from './state' export const getters: GetterTree<MeasureState, RootState> = { // getTestStr: (state) => state.test.toString() + 'str', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/enum-constant.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 11:08:55 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/toolbar/enum-constant.ts */ export enum ToolbarHandlerEnum { RESET_STATE = 'RESET_STATE', SET_VISIBLE = 'SET_VISIBLE', SET_DROP_DOWN = 'SET_DROP_DOWN', // elevation contour SET_ELEVATION_CONTURE_ACTIVE = 'SET_ELEVATION_CONTURE_ACTIVE', // terrain sampling SET_TERRAIN_SAMPLING = 'SET_TERRAIN_SAMPLING', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/other/actions.ts
<gh_stars>0 import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { OtherState } from './state' import { OtherMutationTypes } from './mutation-types' import { OtherActionTypes } from './action-types' import { ClickHandlerOption } from '@/components/jt-toolbar/config/contents/Types' export const actions: ActionTree<OtherState, RootState> = { async [OtherActionTypes.RESET_STATE]({ commit }) { commit(OtherMutationTypes.RESET_STATE) }, // other async [OtherActionTypes.SWITCH_DEPTH_TEST_AGAINST_TERRAIN]( { commit, state }, options: ClickHandlerOption ) { const { viewer } = options if (!viewer) { return } const switchTo = !state.depthTestAgainstTerrain viewer.scene.globe.depthTestAgainstTerrain = switchTo commit(OtherMutationTypes.SET_DEPTH_TEST_AGAINST_TERRAIN, switchTo) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/state.ts
<reponame>CN-3211/vt-cesium2.0 export type DrawState = { drawPointActive: boolean drawPolylineActive: boolean drawPolygonActive: boolean } export const defaultState = (): DrawState => { return { drawPointActive: false, drawPolylineActive: false, drawPolygonActive: false, } } export const state: DrawState = defaultState()
CN-3211/vt-cesium2.0
src/constant/index.ts
/* * @Date: 2021-06-17 16:01:31 * @LastEditors: huangzh873 * @LastEditTime: 2021-11-22 11:37:40 * @FilePath: \cesium-web-vue\src\constant\index.ts */ const enum direction { LEFT = "Left", RIGHT = "Right", TOP = "Top", BOTTOM = "Bottom", EAST = "East", WEST = "West", SOUTH = "South", NORTH = "North" } const CESIUM_3D_TILE = 'CESIUM_3D_TILE' const TERRAIN = 'TERRAIN' export { direction, CESIUM_3D_TILE, TERRAIN }
CN-3211/vt-cesium2.0
src/@types/shims-cesium.d.ts
/* * @Date: 2022-03-30 14:57:01 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 16:36:14 * @FilePath: /vt-cesium2.0/src/@types/shims-cesium.d.ts */ // 支持在原来的.d.ts下新增自己定义的属性,如jt declare module 'cesium' { import('cesium') import { ImageryLayer, Viewer } from 'cesium' import Jt from '@/libs/cesium/cesium-jt' import ImageryLayerCoordinateTransform from '@/libs/cesium/libs/sus-imagery-layer-coordinate-transform/ImageryLayerCoordinateTransform' import PrimitiveManager from '@/libs/cesium/libs/primitive-manager/PrimitiveManager' interface ImageryLayer { name: string uuid: string coordinateTransform: ?ImageryLayerCoordinateTransform } interface Viewer { jt?: Jt } interface Model { name: string uuid: string _PriManagFlag: string } interface Cesium3DTileset { name: string uuid: string _PriManagFlag: string } }
CN-3211/vt-cesium2.0
src/libs/utils/vue-const.ts
const PROPERTY_CHANGE_EVENT = 'propertyChange' const UPDATE_MODEL_EVENT = 'update:modelValue' export { PROPERTY_CHANGE_EVENT, UPDATE_MODEL_EVENT }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/imagery-manager/ImageryManager.ts
import { Viewer, ImageryLayer } from 'cesium' import * as Cesium from 'cesium' import ImageryLayerCoordinateTransform, { CoordinateType, } from '@/libs/cesium/libs/imagery-layer-coordinate-transform/ImageryLayerCoordinateTransform' import { uuid } from '@/utils' export type ImagerySource = { name: string iconImageUrl: string providerName: string afterReady?: (viewer: Viewer, success: boolean) => void options?: any coordinateType?: CoordinateType } export type Imagery = { name: string uuid: string providerName: string show: boolean cesiumLayerIndex: number } class ImageryManager { private viewer: Viewer public imageries: Imagery[] = [] constructor(viewer: Viewer) { this.viewer = viewer } public syncImageries(): Imagery[] { const { viewer } = this this.imageries.splice(0, this.imageries.length) const ils = viewer.imageryLayers const len = ils.length for (let i = len - 1; i >= 0; --i) { const layer: ImageryLayer = ils.get(i) this.imageries.push({ name: layer.name || '<Unknown>', uuid: layer.uuid || '<Unknown>', providerName: layer.imageryProvider.constructor.name, show: layer.show, cesiumLayerIndex: i, }) } return this.imageries } public addImagery(item: ImagerySource): ImageryLayer | undefined { const { viewer } = this const provider = new (Cesium as any)[item.providerName]({ ...(item.options || {}), }) provider.readyPromise.then((success: boolean): void => { item.afterReady && item.afterReady(viewer, success) }) const layer = new ImageryLayer(provider) layer.name = item.name layer.uuid = uuid() if (item.coordinateType) { layer.coordinateTransform = new ImageryLayerCoordinateTransform( layer, item.coordinateType, true ) } const ils = viewer.imageryLayers ils.add(layer) this.syncImageries() return layer } public getLayer(index: number): ImageryLayer { this.syncImageries() return this.viewer.imageryLayers.get(this.imageries[index].cesiumLayerIndex) } public removeLayer(index: number): void { this.viewer.imageryLayers.remove(this.getLayer(index)) this.syncImageries() } public removeAll(): void { this.viewer.imageryLayers.removeAll() this.syncImageries() } } export default ImageryManager
CN-3211/vt-cesium2.0
src/utils/vue-utils/limitGlobe/index.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2021-10-11 09:52:07 * @LastEditors: huangzh873 * @LastEditTime: 2021-10-11 09:58:53 * @FilePath: \cesium-web-vue\src\utils\vue-utils\limitGlobe\index.ts */ import * as Cesium from 'cesium'; export default class limitClip { constructor(viewer: Cesium.Viewer) { // limitClip.createGlobeClip(viewer); limitClip.useGlobeLimit(viewer) } /** * @description: 通过地形裁剪的方式来切割地球 * @param {*} viewer * @return {*} */ private static createGlobeClip(viewer: Cesium.Viewer) { const clippingPlanes = new Cesium.ClippingPlaneCollection({ planes: [ new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, 1.0, 0.0), 4000000.0), new Cesium.ClippingPlane(new Cesium.Cartesian3(0.0, -1.0, 0.0), 4000000.0), ], unionClippingRegions: true, edgeColor: Cesium.Color.WHITE, edgeWidth: 1.0 }) viewer.scene.globe.clippingPlanes = clippingPlanes } private static useGlobeLimit(viewer: Cesium.Viewer) { const limitRectangle = Cesium.Rectangle.fromDegrees(109.33, 30.09, 110.33, 31.32); viewer.scene.globe.cartographicLimitRectangle = limitRectangle; // 添加切面边缘 viewer.entities.add({ rectangle: { fill: false, coordinates: limitRectangle, outline: true, outlineColor: Cesium.Color.WHITE } }) } }
CN-3211/vt-cesium2.0
src/components/toolbarGroup/Scenes/rain.ts
<reponame>CN-3211/vt-cesium2.0<gh_stars>0 /* * @Date: 2022-01-10 11:41:52 * @LastEditors: huangzh873 * @LastEditTime: 2022-01-10 14:25:02 * @FilePath: /cesium-web-vue/src/components/toolbarGroup/Scenes/rain.ts */ import { PostProcessStage, Viewer } from 'cesium'; // 要改 // const RainShader = require('./rain.glsl') // console.log('RainShader :>> ', RainShader); class rainEffect { rainPostProcessStage: undefined | PostProcessStage startRainEffect(viewer: Viewer) { this.rainPostProcessStage = this.createRainPostProcessStage() viewer.scene.postProcessStages.add(this.rainPostProcessStage) } stopRainEffect(viewer: Viewer) { if(this.rainPostProcessStage) { viewer.scene.postProcessStages.remove(this.rainPostProcessStage) this.rainPostProcessStage = undefined; } } createRainPostProcessStage() { return new PostProcessStage({ fragmentShader: `uniform sampler2D colorTexture; varying vec2 v_textureCoordinates; uniform float speed; float hash(float x){ return fract(sin(x*23.3)*13.13); } void main(){ float time = czm_frameNumber * speed / 1000.0; vec2 resolution = czm_viewport.zw; vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y); vec3 c=vec3(.1,.2,.3); float a=-.3; float si=sin(a),co=cos(a); uv*=mat2(co,-si,si,co); uv*=length(uv+vec2(0,4.9))*.3+1.; float v=1.-sin(hash(floor(uv.x*100.))*2.); float b=clamp(abs(sin(20.*time*v+uv.y*(5./(2.+v))))-.95,0.,1.)*10.; c*=v*b; gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(c,1), 0.5); }`, uniforms: { speed: 10 } }) } } /** 下雨特效开始 */ export default rainEffect /** 雨天特效结束 */
CN-3211/vt-cesium2.0
src/libs/cesium/libs/classification/Classification.ts
import { Viewer, Color, ClassificationType, ScreenSpaceEventHandler, defined, ScreenSpaceEventType, Primitive, Geometry, GeometryFactory, ClassificationPrimitive, GeometryInstance, ColorGeometryInstanceAttribute, } from 'cesium' type Classified = { id: string | undefined primitive: Primitive | undefined color: Color | undefined } type AddClassificationOption = { color?: number[] } type InvertClassificationOption = { invert: boolean } type Add3DTileClassificationPrimitiveOption = { id: string geometry: Geometry | GeometryFactory } type remove3DTileClassificationPrimitiveOption = { id: string } class Classification { private viewer: Viewer private classified: Classified = { id: undefined, primitive: undefined, color: undefined, } constructor(viewer: Viewer) { this.viewer = viewer } public removeClassification(): void { const { primitive, color, id } = this.classified if ( primitive && defined(primitive) && defined(primitive.getGeometryInstanceAttributes) ) { const attributes = primitive.getGeometryInstanceAttributes(id) attributes.color = color this.classified.id = undefined this.classified.primitive = undefined this.classified.color = undefined } } public addClassification( option: AddClassificationOption ): ScreenSpaceEventHandler | undefined { const { color } = option const { scene } = this.viewer const self = this const handler = new ScreenSpaceEventHandler(scene.canvas) handler.setInputAction(function (movement) { const pickedObject = scene.pick(movement.endPosition) if (pickedObject && defined(pickedObject) && defined(pickedObject.id)) { if (pickedObject.id === self.classified.id) { return } if (self.classified.id && defined(self.classified.id)) { self.removeClassification() } } if ( defined(pickedObject) && defined(pickedObject.primitive) && defined(pickedObject.id) && defined(pickedObject.primitive.getGeometryInstanceAttributes) ) { self.classified.id = pickedObject.id self.classified.primitive = pickedObject.primitive if (self.classified.primitive) { const attributes = self.classified.primitive.getGeometryInstanceAttributes( self.classified.id ) self.classified.color = attributes.color attributes.color = color || [0, 255, 0, 128] } } else if (defined(self.classified.id)) { self.removeClassification() } }, ScreenSpaceEventType.MOUSE_MOVE) return handler } private invertClassification(option: InvertClassificationOption): void { const { invert } = option const { scene } = this.viewer scene.invertClassification = invert scene.invertClassificationColor = new Color(0.1, 0.1, 0.1, 0) } public addInvertClassification(): ScreenSpaceEventHandler { const { scene } = this.viewer const self = this const handler = new ScreenSpaceEventHandler(scene.canvas) handler.setInputAction(function (movement) { const pickedObject = scene.pick(movement.position) if ( pickedObject && defined(pickedObject) && defined(pickedObject.primitive) && defined(pickedObject.id) && defined(pickedObject.primitive.getGeometryInstanceAttributes) ) { const toValue = !scene.invertClassification self.invertClassification({ invert: toValue }) } }, ScreenSpaceEventType.LEFT_CLICK) return handler } public removeInvertClassification(): void { this.invertClassification({ invert: false }) } public add3DTileClassificationPrimitive( option: Add3DTileClassificationPrimitiveOption ): void { const { id, geometry } = option const { scene } = this.viewer scene.primitives.add( new ClassificationPrimitive({ geometryInstances: new GeometryInstance({ id: id, geometry: geometry, attributes: { color: ColorGeometryInstanceAttribute.fromColor( new Color(1.0, 0.0, 0.0, 0) ), }, }), classificationType: ClassificationType.CESIUM_3D_TILE, }) ) } public remove3DTileClassificationPrimitive( option: remove3DTileClassificationPrimitiveOption ): void { const { id } = option const { primitives } = this.viewer.scene const len = primitives.length for (let i = 0; i < len; i++) { const p = primitives.get(i) if (!(p instanceof ClassificationPrimitive)) { continue } if (id.indexOf((p as any)._primitive._instanceIds) !== -1) { primitives.remove(p) } } } } export default Classification
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/view/groups/index.ts
import { Group } from '../../Types' import state from './status' import flyTo from './fly-to' import view from './view' const groups: Array<Group> = [flyTo, state, view] export default groups
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/tool/groups/index.ts
<gh_stars>0 /* * @Date: 2022-04-06 16:45:35 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-06 16:56:10 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/tool/groups/index.ts */ import { Group } from '../../Types' import threeDTiles from './3d-tiles' import draw from './draw' import measure from './measure' import model from './model' const groups: Array<Group> = [ draw, measure ] export default groups
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/locationbar/getters.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 10:44:30 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/locationbar/getters.ts */ import { GetterTree } from 'vuex' import { RootState } from '@/store' import { State } from './state' import { GetterEnum } from './enum-constant' export type Getter = { [GetterEnum.ALL_SHOW](state: State): boolean } export const getters: GetterTree<State, RootState> & Getter = { [GetterEnum.ALL_SHOW](state) { return state.showCameraLocation || state.showFPS || state.showMouseLocation }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/other/action-types.ts
<reponame>CN-3211/vt-cesium2.0<gh_stars>0 export enum OtherActionTypes { RESET_STATE = 'RESET_STATE', // other SWITCH_DEPTH_TEST_AGAINST_TERRAIN = 'SWITCH_DEPTH_TEST_AGAINST_TERRAIN', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/actions.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/draw/actions.ts import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { DrawState } from './state' import { DrawMutationTypes } from './mutation-types' import { DrawActionTypes } from './action-types' export const actions: ActionTree<DrawState, RootState> = { async [DrawActionTypes.RESET_STATE]({ commit }) { commit(DrawMutationTypes.RESET_STATE) }, // draw async [DrawActionTypes.SET_DRAW_POINT_ACTIVE]({ commit }, payload: boolean) { commit(DrawMutationTypes.SET_DRAW_POINT_ACTIVE, payload) }, async [DrawActionTypes.SET_DRAW_POLYLINE_ACTIVE]( { commit }, payload: boolean ) { commit(DrawMutationTypes.SET_DRAW_POLYLINE_ACTIVE, payload) }, async [DrawActionTypes.SET_DRAW_POLYGON_ACTIVE]( { commit }, payload: boolean ) { commit(DrawMutationTypes.SET_DRAW_POLYGON_ACTIVE, payload) }, }
CN-3211/vt-cesium2.0
src/libs/utils/uuid.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2022-03-30 16:45:49 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-30 16:46:11 * @FilePath: /vt-cesium2.0/src/libs/utils/uuid.ts */ const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('') const uuid = function (): string { const uuid:any[] = [] uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-' let r for (let i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | (Math.random() * 16) uuid[i] = CHARS[i === 19 ? (r & 0x3) | 0x8 : r] } } return uuid.join('') } export default uuid
CN-3211/vt-cesium2.0
src/utils/c-utils.ts
<filename>src/utils/c-utils.ts /* * @Date: 2021-06-16 15:54:32 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-29 18:35:42 * @FilePath: /vt-cesium2.0/src/utils/c-utils.ts */ import { Math as CMath, Viewer, Cartesian2, Cartesian3, Ellipsoid, EllipsoidTerrainProvider, Model, Cesium3DTileset, Cesium3DTileFeature, Cartographic, ScreenSpaceEventHandler, ScreenSpaceEventType } from 'cesium'; /** * @description: 根据用户输入的type来直接创建hanlder * @param {HTMLCanvasElement} [canvas] * @param {function} [callback] 事件发生时的回调函数 * @param {ScreenSpaceEventType} [type] 事件类型 * @return {ScreenSpaceEventHandler} 返回包装后的事件 */ function createHandler(canvas: HTMLCanvasElement, callback: (...params: any[]) => any, type: ScreenSpaceEventType): ScreenSpaceEventHandler { const handler: ScreenSpaceEventHandler = new ScreenSpaceEventHandler(canvas) handler.setInputAction(callback, type) return handler } function changeCar3ToLnglat(car3: Cartesian3) { const cartographic = Cartographic.fromCartesian(car3); const lng = CMath.toDegrees(cartographic.longitude); const lat = CMath.toDegrees(cartographic.latitude); const height = cartographic.height; return { lng: Number(lng.toFixed(6)), lat: Number(lat.toFixed(6)), height: Number(height.toFixed(2)), _lng: lng, _lat: lat, _height: height } } /** * 拾取位置点,能够根据鼠标位置判断出是画在3dtils上,还是画在地球上,还是画在地形上 * * @param {Object} px 屏幕坐标 * * @return {Object} Cartesian3 三维坐标 */ function getCatesian3FromPX(px: Cartesian2, viewer: Viewer) { const picks = viewer.scene.drillPick(px); let cartesian; let isOn3dtiles = false, isOnTerrain = false; // drillPick for (const i in picks) { const pick = picks[i]; if ( (pick && pick.primitive instanceof Cesium3DTileFeature) || (pick && pick.primitive instanceof Cesium3DTileset) || (pick && pick.primitive instanceof Model) ) { //模型上拾取 isOn3dtiles = true; } // 3dtilset if (isOn3dtiles) { // viewer.scene.pick(px); // pick cartesian = viewer.scene.pickPosition(px); if (cartesian) { const cartographic = Cartographic.fromCartesian(cartesian); if (cartographic.height < 0) cartographic.height = 0; const lon = CMath.toDegrees(cartographic.longitude), lat = CMath.toDegrees(cartographic.latitude), height = cartographic.height; cartesian = transformWGS84ToCartesian({ lng: lon, lat: lat, alt: height, }, viewer); } } } // 地形 const isEllipsoidTerrainProvider = viewer.terrainProvider instanceof EllipsoidTerrainProvider; // Terrain if (!isOn3dtiles && !isEllipsoidTerrainProvider) { const ray = viewer.scene.camera.getPickRay(px); if (!ray) return null; cartesian = viewer.scene.globe.pick(ray, viewer.scene); isOnTerrain = true; } // 地球 if (!isOn3dtiles && !isOnTerrain && isEllipsoidTerrainProvider) { cartesian = viewer.scene.camera.pickEllipsoid(px, viewer.scene.globe.ellipsoid); } if (cartesian) { const position = transformCartesianToWGS84(cartesian, viewer); if (position && position.alt < 0) { cartesian = transformWGS84ToCartesian(position, viewer, 0.1); } return cartesian; } return false; } /*** * 坐标转换 笛卡尔转84 * * @param {Object} Cartesian3 三维位置坐标 * * @return {Object} {lng,lat,alt} 地理坐标 */ function transformCartesianToWGS84(cartesian: any, viewer: Viewer) { if (viewer && cartesian) { const ellipsoid = Ellipsoid.WGS84; const cartographic = ellipsoid.cartesianToCartographic(cartesian); return { lng: CMath.toDegrees(cartographic.longitude), lat: CMath.toDegrees(cartographic.latitude), alt: cartographic.height, }; } } /*** * 坐标转换 84转笛卡尔 * * @param {Object} {lng,lat,alt} 地理坐标 * * @return {Object} Cartesian3 三维位置坐标 */ function transformWGS84ToCartesian(position: any, viewer: Viewer, alt?: any) { if (viewer) { return position ? Cartesian3.fromDegrees( position.lng || position.lon, position.lat, position.alt = alt || position.alt, Ellipsoid.WGS84 ) : Cartesian3.ZERO } } export { createHandler, changeCar3ToLnglat, getCatesian3FromPX }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/state.ts
<gh_stars>0 export type NatureState = { showSun: boolean showMoon: boolean showSkyAtmosphere: boolean enableLighting: boolean showSkyBox: boolean showShadow: boolean } export const defaultState = (): NatureState => { return { showSun: true, showMoon: false, showSkyAtmosphere: true, enableLighting: false, showSkyBox: true, showShadow: false, } } export const state: NatureState = defaultState()
CN-3211/vt-cesium2.0
src/resources/sample-data/index.ts
type SampleDataConfig = { terrain: string 'satellite-base': string 'sample-data-base': string } const sampleDataConfigDefault: SampleDataConfig = { terrain: 'https://sample-data-terrain.vercel.app/', 'satellite-base': 'https://sample-data-satellite.vercel.app/', 'sample-data-base': 'https://sample-data-jt.vercel.app/', } const sampleDataConfigStr = process.env.VUE_APP_SAMPLE_DATA_CONFIG as string let sampleDataConfig: SampleDataConfig try { sampleDataConfig = JSON.parse(sampleDataConfigStr) as SampleDataConfig } catch (e) { console.warn('Sample data config error.', e) sampleDataConfig = sampleDataConfigDefault } export default { satellite: `${sampleDataConfig['satellite-base']}{z}/{x}/{y}.png`, terrain: sampleDataConfig.terrain, 'my-home': `${sampleDataConfig['sample-data-base']}my-home/3dtile/tileset.json`, 'cd-buildings': `${sampleDataConfig['sample-data-base']}cd-buildings/3dtile/tileset.json`, 'shp-factory': `${sampleDataConfig['sample-data-base']}shp-factory/tileset.json`, apartment: `${sampleDataConfig['sample-data-base']}apartment/tileset.json`, rc: `${sampleDataConfig['sample-data-base']}rc/rc.gltf`, }
CN-3211/vt-cesium2.0
src/store/modules/template/action-types.ts
export enum TemplateActionTypes { RESET_STATE = 'RESET_STATE', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/imagery/actions.ts
import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { ImageryState, SplitType } from './state' import { ImageryMutationTypes } from './mutation-types' import { ImageryActionTypes } from './action-types' export const actions: ActionTree<ImageryState, RootState> = { async [ImageryActionTypes.RESET_STATE]({ commit }) { commit(ImageryMutationTypes.RESET_STATE) }, // imagery async [ImageryActionTypes.SET_SPLIT]({ commit, state }, payload: SplitType) { commit(ImageryMutationTypes.SET_SPLIT, payload) }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/action-types.ts
export enum Tool3DTileActionTypes { RESET_STATE = 'RESET_STATE', // tool3dtile SET_HIGHLIGHT_3DTILE_FEATURE_ACTIVE = 'SET_HIGHLIGHT_3DTILE_FEATURE_ACTIVE', SET_HOVER_CLASSIFICATION_ACTIVE = 'SET_HOVER_CLASSIFICATION_ACTIVE', SET_CLICK_CLASSIFICATION_ACTIVE = 'SET_CLICK_CLASSIFICATION_ACTIVE', }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/getters.ts
import { GetterTree } from 'vuex' import { RootState } from '@/store' import { Tool3DTileState } from './state' export const getters: GetterTree<Tool3DTileState, RootState> = { // getTestStr: (state) => state.test.toString() + 'str', }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/Types.ts
<reponame>CN-3211/vt-cesium2.0 /* * @Date: 2022-03-28 09:56:52 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-06 16:51:39 * @FilePath: /vt-cesium2.0/src/components/jt-toolbar/config/contents/Types.ts */ import type { Viewer } from 'cesium'; import type { RootState } from '@/store' import { Store } from 'vuex' import { Router } from 'vue-router' export type OnMountedOption = { viewer?: Viewer iconEl?: HTMLElement store: Store<RootState> } export type OnMounted = (option: OnMountedOption) => void export type Content = { name: string groups: Array<Group> invisible?: boolean disable?: boolean } export type Group = { name: string items: Array<Item> invisible?: boolean disable?: boolean } export type ActiveOption = { store: Store<RootState> } export type Active = (option: ActiveOption) => boolean export type ClickHandler = (option: ClickHandlerOption) => void | any export type Item = { // string for name, function for i18n convert name: string icon: string invisible?: boolean disable?: boolean onMounted?: OnMounted clickHandler?: ClickHandler clickHandlerResult?: any active?: Active // if true, clickHandler / clickHandlerResult will not execute, and dropdown arrow will not show dropdownOnClick?: boolean dropdown?: Dropdown } export type ClickHandlerOption = { viewer?: Viewer item?: Item router?: Router store: Store<RootState> } export type Dropdown = { componentName: string } const x = { name: '视图', groups: [ { name: '视角', items: [ { name: '全球', icon: 'earth', clickHandler: undefined, }, ], }, ], }
CN-3211/vt-cesium2.0
src/libs/cesium/mixins/logMousePositionMixin.ts
import * as Cesium from 'cesium' type Options = { withHeight: boolean } function logMousePositionMixin( viewer: Cesium.Viewer, options: Options = { withHeight: false, } ): void { if (!viewer || !Cesium.defined(viewer)) { throw new Cesium.DeveloperError('viewer is required.') } const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas) handler.setInputAction(function (e) { let position: Cesium.Cartesian3 | undefined if (options.withHeight) { viewer.scene.globe.depthTestAgainstTerrain = true position = viewer.scene.pickPosition(e.position) } else { position = viewer.scene.camera.pickEllipsoid( e.position, viewer.scene.globe.ellipsoid ) } if (!position) { return } const cartographic = Cesium.Cartographic.fromCartesian(position) const longitude = Cesium.Math.toDegrees(cartographic.longitude) const latitude = Cesium.Math.toDegrees(cartographic.latitude) const height = cartographic.height console.log(longitude, latitude, height) }, Cesium.ScreenSpaceEventType.LEFT_CLICK) ;(viewer as any)[additionPropertyName] = { handler: handler, } } const additionPropertyName = 'jtLogMousePositionMixin' export { additionPropertyName } export default logMousePositionMixin
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/actions.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/store/modules/jt-cesium-vue/modules/toolbar/actions.ts /* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-01 14:04:20 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/toolbar/actions.ts */ import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { State, DropdownState, TerrainSamplingState } from './state' import { ToolbarHandlerEnum } from './enum-constant' export const actions: ActionTree<State, RootState> = { async [ToolbarHandlerEnum.RESET_STATE]({ commit }) { commit(ToolbarHandlerEnum.RESET_STATE) }, async [ToolbarHandlerEnum.SET_VISIBLE]({ commit }, payload: boolean) { commit(ToolbarHandlerEnum.SET_VISIBLE, payload) }, async [ToolbarHandlerEnum.SET_DROP_DOWN]({ commit }, payload: DropdownState) { commit(ToolbarHandlerEnum.SET_DROP_DOWN, payload) }, // elevation contour async [ToolbarHandlerEnum.SET_ELEVATION_CONTURE_ACTIVE]( { commit }, payload: boolean ) { commit(ToolbarHandlerEnum.SET_ELEVATION_CONTURE_ACTIVE, payload) }, // terrain sampling async [ToolbarHandlerEnum.SET_TERRAIN_SAMPLING]( { commit }, payload: TerrainSamplingState ) { commit(ToolbarHandlerEnum.SET_TERRAIN_SAMPLING, payload) }, }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/calculate-primitive-center/index.ts
import { Cesium3DTileset, Model, Matrix4, Cartesian3, Cartographic, Math, } from 'cesium' type CenterLocation = { longitude: number latitude: number height: number } export default function (primitive: Cesium3DTileset | Model): CenterLocation { let center: any if (primitive instanceof Cesium3DTileset) { center = primitive.boundingSphere.center } if (primitive instanceof Model) { center = Matrix4.multiplyByPoint( primitive.modelMatrix, primitive.boundingSphere.center, new Cartesian3() ) } const cartographic = Cartographic.fromCartesian(center) const longitude = Math.toDegrees(cartographic.longitude) const latitude = Math.toDegrees(cartographic.latitude) const height = cartographic.height return { longitude, latitude, height } }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/primitive-manager/PrimitiveManager.ts
import { Viewer, Color, HeightReference, Cesium3DTileset, Model, Resource, ShadowMode, Matrix4, ClippingPlaneCollection, ClassificationType, Ellipsoid, Cartesian2, Cartesian3, Scene, DistanceDisplayCondition, ColorBlendMode, Credit, } from 'cesium' import { uuid } from '@/utils' export type JTPrimitive = { name: string uuid: string show: boolean cesiumPrimitiveIndex: number } class PrimitiveManager { private viewer: Viewer public jtPrimitives: JTPrimitive[] = [] public static PRIMITIVE_MANAGER_FLAG_VALUE = '__JT_PRI_F' constructor(viewer: Viewer) { this.viewer = viewer } public syncJTPrimitives( inManagedPrimitiveOnly: boolean = true ): JTPrimitive[] { this.jtPrimitives.splice(0, this.jtPrimitives.length) const pris = this.viewer.scene.primitives const len = pris.length for (let i = len - 1; i >= 0; --i) { const model = pris.get(i) if (!(model instanceof Cesium3DTileset || model instanceof Model)) { continue } if ( inManagedPrimitiveOnly && model._PriManagFlag !== PrimitiveManager.PRIMITIVE_MANAGER_FLAG_VALUE ) { continue } this.jtPrimitives.push({ name: model.name || '<NoneName>', uuid: model.uuid || '<NoneUuid>', show: model.show, cesiumPrimitiveIndex: i, }) } return this.jtPrimitives } public add3DTileset(option: { name: string // cesium default url: Resource | string | Promise<Resource> | Promise<string> show?: boolean modelMatrix?: Matrix4 shadows?: ShadowMode maximumScreenSpaceError?: number maximumMemoryUsage?: number cullWithChildrenBounds?: boolean cullRequestsWhileMoving?: boolean cullRequestsWhileMovingMultiplier?: number preloadWhenHidden?: boolean preloadFlightDestinations?: boolean preferLeaves?: boolean dynamicScreenSpaceError?: boolean dynamicScreenSpaceErrorDensity?: number dynamicScreenSpaceErrorFactor?: number dynamicScreenSpaceErrorHeightFalloff?: number progressiveResolutionHeightFraction?: number foveatedScreenSpaceError?: boolean foveatedConeSize?: number foveatedMinimumScreenSpaceErrorRelaxation?: number foveatedInterpolationCallback?: Cesium3DTileset.foveatedInterpolationCallback foveatedTimeDelay?: number skipLevelOfDetail?: boolean baseScreenSpaceError?: number skipScreenSpaceErrorFactor?: number skipLevels?: number immediatelyLoadDesiredLevelOfDetail?: boolean loadSiblings?: boolean clippingPlanes?: ClippingPlaneCollection classificationType?: ClassificationType ellipsoid?: Ellipsoid pointCloudShading?: any imageBasedLightingFactor?: Cartesian2 lightColor?: Cartesian3 luminanceAtZenith?: number sphericalHarmonicCoefficients?: Cartesian3[] specularEnvironmentMaps?: string backFaceCulling?: boolean showOutline?: boolean vectorClassificationOnly?: boolean vectorKeepDecodedPositions?: boolean debugHeatmapTilePropertyName?: string debugFreezeFrame?: boolean debugColorizeTiles?: boolean debugWireframe?: boolean debugShowBoundingVolume?: boolean debugShowContentBoundingVolume?: boolean debugShowViewerRequestVolume?: boolean debugShowGeometricError?: boolean debugShowRenderingStatistics?: boolean debugShowMemoryUsage?: boolean debugShowUrl?: boolean }): Cesium3DTileset { const c3Dtileset = new Cesium3DTileset({ ...option, }) c3Dtileset._PriManagFlag = PrimitiveManager.PRIMITIVE_MANAGER_FLAG_VALUE c3Dtileset.name = option.name c3Dtileset.uuid = uuid() c3Dtileset.show = option.show || false this.viewer.scene.primitives.add(c3Dtileset) this.syncJTPrimitives() return c3Dtileset } public addGltf(option: { name: string // cesium default url: Resource | string basePath?: Resource | string show?: boolean modelMatrix?: Matrix4 scale?: number minimumPixelSize?: number maximumScale?: number id?: any allowPicking?: boolean incrementallyLoadTextures?: boolean asynchronous?: boolean clampAnimations?: boolean shadows?: ShadowMode debugShowBoundingVolume?: boolean debugWireframe?: boolean heightReference?: HeightReference scene?: Scene distanceDisplayCondition?: DistanceDisplayCondition color?: Color colorBlendMode?: ColorBlendMode colorBlendAmount?: number silhouetteColor?: Color silhouetteSize?: number clippingPlanes?: ClippingPlaneCollection dequantizeInShader?: boolean credit?: Credit | string backFaceCulling?: boolean showOutline?: boolean }): Model { const gltf = Model.fromGltf({ ...option, }) gltf._PriManagFlag = PrimitiveManager.PRIMITIVE_MANAGER_FLAG_VALUE gltf.name = option.name gltf.uuid = uuid() gltf.show = option.show || false this.viewer.scene.primitives.add(gltf) this.syncJTPrimitives() return gltf } public getPrimitiveByJTPrimitiveIndex( index: number, inManagedPrimitiveOnly: boolean = true ): any { this.syncJTPrimitives(inManagedPrimitiveOnly) return this.viewer.scene.primitives.get( this.jtPrimitives[index].cesiumPrimitiveIndex ) } public getPrimitiveByJTPrimitive(jtPrimitive: JTPrimitive): any { return this.viewer.scene.primitives.get(jtPrimitive.cesiumPrimitiveIndex) } public removePrimitive( index: number, inManagedPrimitiveOnly: boolean = true ): void { this.viewer.scene.primitives.remove( this.getPrimitiveByJTPrimitiveIndex(index, inManagedPrimitiveOnly) ) this.syncJTPrimitives(inManagedPrimitiveOnly) } public removeAll(inManagedPrimitiveOnly: boolean = true): void { let model = this.viewer.scene.primitives.get(0) while (model) { if (model instanceof Cesium3DTileset || model instanceof Model) { if ( inManagedPrimitiveOnly && model._PriManagFlag !== PrimitiveManager.PRIMITIVE_MANAGER_FLAG_VALUE ) { continue } this.viewer.scene.primitives.remove(model) } model = this.viewer.scene.primitives.get(0) } this.syncJTPrimitives(inManagedPrimitiveOnly) } } export default PrimitiveManager
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/locationbar/enum-constant.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-04-02 10:44:13 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/modules/locationbar/enum-constant.ts */ export enum LocationbarHandlerEnum { RESET_STATE = 'RESET_STATE', SET_SHOW_CAMERA_LOCATION = 'SET_SHOW_CAMERA_LOCATION', SET_SHOW_MOUSE_LOCATION = 'SET_SHOW_MOUSE_LOCATION', SET_SHOW_FPS = 'SET_SHOW_FPS', } export enum GetterEnum { ALL_SHOW = 'ALL_SHOW', }
CN-3211/vt-cesium2.0
src/libs/cesium/libs/elevation-contour/ElevationContour.ts
<filename>src/libs/cesium/libs/elevation-contour/ElevationContour.ts import { Viewer, Material } from 'cesium' class ElevationContour { private viewer: Viewer constructor(viewer: Viewer) { this.viewer = viewer } public show(): void { const { viewer } = this viewer.scene.globe.material = Material.fromType('ElevationContour') } public remove(): void { const { viewer } = this ;(viewer.scene.globe.material as any) = undefined } } export default ElevationContour
CN-3211/vt-cesium2.0
src/libs/cesium/libs/percentage-change/PercentageChange.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/libs/cesium/libs/percentage-change/PercentageChange.ts<gh_stars>0 import { Viewer } from 'cesium' class PercentageChange { private viewer: Viewer constructor(viewer: Viewer) { this.viewer = viewer } set(percentageChanged: number = 0.5): void { if (percentageChanged > 1 || percentageChanged < 0) { percentageChanged = 0.1 } this.viewer.camera.percentageChanged = percentageChanged } get(): number { return this.viewer.camera.percentageChanged } } export default PercentageChange
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/actions.ts
<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/tool3DTile/actions.ts import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { Tool3DTileState } from './state' import { Tool3DTileMutationTypes } from './mutation-types' import { Tool3DTileActionTypes } from './action-types' export const actions: ActionTree<Tool3DTileState, RootState> = { async [Tool3DTileActionTypes.RESET_STATE]({ commit }) { commit(Tool3DTileMutationTypes.RESET_STATE) }, async [Tool3DTileActionTypes.SET_HIGHLIGHT_3DTILE_FEATURE_ACTIVE]( { commit }, payload: boolean ) { commit(Tool3DTileMutationTypes.SET_HIGHLIGHT_3DTILE_FEATURE_ACTIVE, payload) }, async [Tool3DTileActionTypes.SET_HOVER_CLASSIFICATION_ACTIVE]( { commit }, payload: boolean ) { commit(Tool3DTileMutationTypes.SET_HOVER_CLASSIFICATION_ACTIVE, payload) }, async [Tool3DTileActionTypes.SET_CLICK_CLASSIFICATION_ACTIVE]( { commit }, payload: boolean ) { commit(Tool3DTileMutationTypes.SET_CLICK_CLASSIFICATION_ACTIVE, payload) }, }
CN-3211/vt-cesium2.0
src/utils/vue-utils/draw/drawUtils.ts
/* * @Date: 2021-06-02 18:14:09 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-29 18:27:15 * @FilePath: /vt-cesium2.0/src/utils/vue-utils/draw/drawUtils.ts */ import { CallbackProperty, Cartesian2, Cartesian3, ClassificationType, Color, defined, Entity, HeightReference, HorizontalOrigin, PolygonHierarchy, Ray, ScreenSpaceEventHandler, ScreenSpaceEventType, VerticalOrigin, Viewer, clone } from 'cesium' import { ref, Ref, watchEffect } from 'vue'; // 选择绘制的模式是在地形上绘制,还是在3dtiles上绘制 export const CESIUM_3D_TILE = 'CESIUM_3D_TILE' export const TERRAIN = 'TERRAIN' class DrawBillboard{ static _viewer: Viewer; handler: ScreenSpaceEventHandler; billboardGroup: Entity[]; positions: Cartesian3[]; constructor(viewer: Viewer) { DrawBillboard._viewer = viewer; this.handler = new ScreenSpaceEventHandler(DrawBillboard._viewer.scene.canvas); this.positions = []; this.billboardGroup = []; } startCreate() { this.handler.setInputAction(Event => { const cartesian:Cartesian3 = this.getCatesian3FromPX(Event.position); if (!cartesian) return; const billboard = this.createBillboard(cartesian); this.billboardGroup.push(billboard); this.positions.push(cartesian); }, ScreenSpaceEventType.LEFT_CLICK) } createBillboard(cartesian:Cartesian3): Entity { return DrawBillboard._viewer.entities.add({ position: cartesian, billboard: { image: 'image/map-marker.png', scale: 0.2, horizontalOrigin: HorizontalOrigin.CENTER, //获取或设置此广告牌的水平原点,确定该广告牌是否为在其锚定位置的左侧,中心或右侧。 verticalOrigin: VerticalOrigin.BOTTOM, //获取或设置此广告牌的垂直原点,以确定该广告牌是否为到其锚定位置的上方,下方或中心。 heightReference:HeightReference.NONE, //获取或设置此广告牌的高度参考 disableDepthTestDistance:Number.MAX_VALUE //获取或设置与相机的距离,在深度处禁用深度测试,例如,以防止剪切地形。设置为零时,将始终应用深度测试。设置为Number.POSITIVE_INFINITY时,永远不会应用深度测试。 } }); } getCatesian3FromPX(px:Cartesian2):Cartesian3 { const cartesian = DrawBillboard._viewer.scene.pickPosition(px); if(!cartesian) { throw new Error("未获取到正确坐标"); } return cartesian } stopDrawing() { this.handler.destroy(); } } interface polylineOptions { drawType: string } class DrawPolyline { static _viewer: Viewer; handler: ScreenSpaceEventHandler; polyline: Entity|undefined = undefined; positions: Cartesian3[] = []; positionsGroup: (Cartesian3[])[] = []; polylineGroup: Entity[] = []; drawType: string = TERRAIN; constructor(viewer: Viewer, options?: polylineOptions) { DrawPolyline._viewer = viewer; this.handler = new ScreenSpaceEventHandler(DrawPolyline._viewer.scene.canvas); options && this.initOptions(options) } initOptions(options: polylineOptions) { Object.keys(options).forEach(item => { this[item] = options[item]; }) } /** * @description: 开始绘制 * @param {function} callback1 - 左键点击后的回调 * @param {function} callback2 - 右键结束后的回调 * @return {*} */ startCreate(callback1?: (params: Cartesian3[]) => void, callback2?: (params: Cartesian3[]) => void): void { this.handler.setInputAction(Event => { const cartesian:Cartesian3 = this.getCatesian3FromPX(Event.position, this.drawType); if(this.positions.length === 0) { this.positions.push(cartesian.clone()) } this.positions.push(cartesian); callback1 && callback1(clone(this.positions)); }, ScreenSpaceEventType.LEFT_CLICK); this.handler.setInputAction(Event => { if(!this.positions.length) { return; } const cartesian = this.getCatesian3FromPX(Event.endPosition, this.drawType) if(this.positions.length === 2 && !defined(this.polyline)) { const _positions = this.positions; this.polyline = this.createPolyline(_positions); } if (this.polyline) { this.positions.pop(); this.positions.push(cartesian); } }, ScreenSpaceEventType.MOUSE_MOVE); this.handler.setInputAction(() => { this.positions.pop(); this.positionsGroup.push(this.positions); if(this.polyline) { this.polylineGroup.push(this.polyline); } this.positions = []; this.polyline = undefined; callback2 && callback2(this.positions); }, ScreenSpaceEventType.RIGHT_CLICK); return; } /** * @description: 将pick到的Cartesian2坐标转化为Cartesian3 * @param {Cartesian2} px * @return {Cartesian3} cartesian */ getCatesian3FromPX(px: Cartesian2, type: string):Cartesian3 { const cartesian = DrawPolyline._viewer.scene.pickPosition(px); if(!cartesian) { throw new Error("未获取到正确坐标"); } return cartesian } createPolyline(_positions: Cartesian3[]):Entity { return DrawPolyline._viewer.entities.add({ polyline: { positions: new CallbackProperty(() => _positions, false), material: Color.YELLOW, width: 3, show: true, clampToGround: true, zIndex: 100000 } }) } stopDrawing() { this.handler.destroy(); this.polyline && DrawPolyline._viewer.entities.remove(this.polyline); } destroy():void { this.polyline = undefined; if(!this.handler.isDestroyed()) { this.handler.destroy() } DrawPolyline._viewer.entities.removeAll(); return } } interface polygonOptions { drawType: string } class DrawPolygon { static _viewer: Viewer; handler: ScreenSpaceEventHandler; positions: Cartesian3[]; polyline: Entity|undefined; polygon: Entity|undefined; positionsGroup: (Cartesian3[])[]; polygonGroup: Entity[]; drawType:string; constructor(viewer: Viewer, options?: polygonOptions) { DrawPolygon._viewer = viewer; this.handler = new ScreenSpaceEventHandler(DrawPolygon._viewer.scene.canvas); this.positions = []; this.polyline = undefined; this.polygon = undefined; this.positionsGroup = []; this.polygonGroup = []; this.drawType = 'TERRAIN'; options && this.initOptions(options) } initOptions(options: polygonOptions) { Object.keys(options).forEach(item => { this[item] = options[item]; }) } startCreate(callback1?: (params: Cartesian3[]) => void, callback2?: (params: Cartesian3[]) => void) { /** 点击开始 **/ this.handler.setInputAction(event => { const clickPosition = this.getCatesian3FromPX(event.position, this.drawType); this.positions.push(clickPosition); callback1 && callback1(clone(this.positions)); }, ScreenSpaceEventType.LEFT_CLICK) /** 鼠标移动 **/ this.handler.setInputAction(event => { if(!this.positions.length) { return; } const movePosition = this.getCatesian3FromPX(event.endPosition, this.drawType); if(this.positions.length > 2) { if(this.polygon) { this.positions.pop(); this.positions.push(movePosition); } else { this.positions.pop(); this.positions.push(movePosition); // 仅仅是改变指针 const _positons = this.positions; this.createPolygon(_positons); } } else { if(this.polyline) { this.positions.pop(); this.positions.push(movePosition); } else { this.positions.push(movePosition); const _positons = this.positions; this.createPolyLine(_positons); } } }, ScreenSpaceEventType.MOUSE_MOVE) /** 右键结束 **/ this.handler.setInputAction(event => { this.positions.pop(); // 这一段防止长度为2时。右键中止绘制后地图上留下线 if(this.positions.length === 2) { this.positions.pop(); } this.positionsGroup.push(this.positions); if(this.polygon) { this.polygonGroup.push(this.polygon); } callback2 && callback2(clone(this.positions)); this.positions = []; this.polyline = undefined; this.polygon = undefined; }, ScreenSpaceEventType.RIGHT_CLICK) } getCatesian3FromPX(px: Cartesian2, type: string):Cartesian3 { const cartesian = DrawPolygon._viewer.scene.pickPosition(px); if(!cartesian) { throw new Error("未获取到正确坐标"); } return cartesian } createPolyLine(_positions: Cartesian3[]) { this.polyline = DrawPolygon._viewer.entities.add({ polyline: { positions: new CallbackProperty(() => _positions.length ? _positions.concat(_positions[0]) : _positions, false), // positions: new CallbackProperty(() => this.positions.length ? this.positions.concat(this.positions[0]) : this.positions, false), material: new Color(0.1, 0.5, 0.9, 0.8), width: 3, show: true, clampToGround: true, } }) } createPolygon(_positions: Cartesian3[]) { this.polygon = DrawPolygon._viewer.entities.add({ polygon: { hierarchy: new CallbackProperty(() => new PolygonHierarchy(_positions), false), material: new Color(0.1, 0.5, 0.9, 0.4), } }) } stopDrawing() { this.handler.destroy(); this.polygon && DrawPolygon._viewer.entities.remove(this.polygon); this.polyline && DrawPolygon._viewer.entities.remove(this.polyline); } destroy(): void { this.polygon = undefined; this.polyline = undefined; if(!this.handler.isDestroyed()) { this.handler.destroy() } DrawPolygon._viewer.entities.removeAll(); } } export { DrawPolyline, DrawPolygon, DrawBillboard, polylineOptions }
CN-3211/vt-cesium2.0
src/components/jt-toolbar/config/contents/tool/groups/measure/index.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/components/jt-toolbar/config/contents/tool/groups/measure/index.ts import { Group, ClickHandlerOption, ActiveOption } from '../../../Types' import { MeasureActionTypes } from '@/store/modules/jt-cesium-vue/modules/toolbar/modules/measure/action-types' import type { MeasureUserCallBackOption } from '@/libs/cesium/libs/measure/Measure' const view: Group = { name: '测量', items: [ { name: '点', icon: 'ruler-point', clickHandler: (option: ClickHandlerOption): void => { if ( !option || !option.viewer || !option.viewer.jt || option.store.state.jtCesiumVue.toolbar.measure.measurePointActive ) { return } const cb: MeasureUserCallBackOption = { started: () => { option.store.dispatch( `jtCesiumVue/toolbar/measure/${MeasureActionTypes.SET_MEASURE_POINT_ACTIVE}`, true ) }, stoped: () => { option.store.dispatch( `jtCesiumVue/toolbar/measure/${MeasureActionTypes.SET_MEASURE_POINT_ACTIVE}`, false ) }, } option.viewer.jt.measure.measurePoint(cb) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.toolbar.measure.measurePointActive }, }, { name: '线', icon: 'ruler-line', clickHandler: (option: ClickHandlerOption): void => { if ( !option || !option.viewer || !option.viewer.jt || option.store.state.jtCesiumVue.toolbar.measure.measurePolylineActive ) { return } const cb: MeasureUserCallBackOption = { started: () => { option.store.dispatch( `jtCesiumVue/toolbar/measure/${MeasureActionTypes.SET_MEASURE_POLYLINE_ACTIVE}`, true ) }, stoped: () => { option.store.dispatch( `jtCesiumVue/toolbar/measure/${MeasureActionTypes.SET_MEASURE_POLYLINE_ACTIVE}`, false ) }, } option.viewer.jt.measure.measurePolyline(cb) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.toolbar.measure .measurePolylineActive }, }, { name: '面', icon: 'polygon2', clickHandler: (option: ClickHandlerOption): void => { if ( !option || !option.viewer || !option.viewer.jt || option.store.state.jtCesiumVue.toolbar.measure.measurePolygonActive ) { return } const cb: MeasureUserCallBackOption = { started: () => { option.store.dispatch( `jtCesiumVue/toolbar/measure/${MeasureActionTypes.SET_MEASURE_POLYGON_ACTIVE}`, true ) }, stoped: () => { option.store.dispatch( `jtCesiumVue/toolbar/measure/${MeasureActionTypes.SET_MEASURE_POLYGON_ACTIVE}`, false ) }, } option.viewer.jt.measure.measurePolygon(cb) }, active: (option: ActiveOption): boolean => { return option.store.state.jtCesiumVue.toolbar.measure .measurePolygonActive }, }, { name: '移除', icon: 'delete', clickHandler: (option: ClickHandlerOption): void => { if (!option || !option.viewer || !option.viewer.jt) { return } option.viewer.jt.measure.removeAllMeasured() }, }, ], } export default view
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/mutations.ts
<reponame>CN-3211/vt-cesium2.0<filename>src/store/modules/jt-cesium-vue/modules/toolbar/modules/nature/mutations.ts<gh_stars>0 import { MutationTree } from 'vuex' import { defaultState } from './state' import type { NatureState } from './state' import { NatureMutationTypes } from './mutation-types' export const mutations: MutationTree<NatureState> = { [NatureMutationTypes.RESET_STATE](state: NatureState) { Object.assign(state, defaultState()) }, // nature [NatureMutationTypes.SET_SHOW_SUN](state: NatureState, payload: boolean) { state.showSun = payload }, [NatureMutationTypes.SET_SHOW_MOON](state: NatureState, payload: boolean) { state.showMoon = payload }, [NatureMutationTypes.SET_SHOW_SKY_ATMOSPHERE]( state: NatureState, payload: boolean ) { state.showSkyAtmosphere = payload }, [NatureMutationTypes.SET_ENABLE_LIGHT](state: NatureState, payload: boolean) { state.enableLighting = payload }, [NatureMutationTypes.SET_SHOW_SKY_BOX](state: NatureState, payload: boolean) { state.showSkyBox = payload }, [NatureMutationTypes.SET_SHOW_SHADOW](state: NatureState, payload: boolean) { state.showShadow = payload }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/index.ts
/* * @Date: 2022-03-30 16:34:56 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-31 17:18:21 * @FilePath: /vt-cesium2.0/src/store/modules/jt-cesium-vue/index.ts */ import { Module } from 'vuex' import { RootState } from '@/store' import { store as locationbar, State as LocationbarState, } from './modules/locationbar' import { store as layout, State as LayoutState } from './modules/layout' import type { ToolbarStateAndModule } from './modules/toolbar' import { store as toolbar } from './modules/toolbar' import type { CesiumDataStateAndModule } from './modules/cesium-data' import { store as cesiumData } from './modules/cesium-data' export type BDCesiumVueState = { locationbar: LocationbarState layout: LayoutState toolbar: ToolbarStateAndModule cesiumData: CesiumDataStateAndModule } export const store: Module<BDCesiumVueState, RootState> = { namespaced: true, modules: { locationbar, layout, toolbar, cesiumData, }, }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/actions.ts
import { ActionTree } from 'vuex' import { RootState } from '@/store' import type { State } from './state' import { CesiumDataMutationTypes } from './mutation-types' import { CesiumDataActionTypes } from './action-types' export const actions: ActionTree<State, RootState> = { async [CesiumDataActionTypes.RESET_STATE]({ commit }) { commit(CesiumDataMutationTypes.RESET_STATE) }, }
CN-3211/vt-cesium2.0
src/components/mapInfo/mapInfo.ts
<reponame>CN-3211/vt-cesium2.0<gh_stars>0 /* * @Date: 2021-12-28 20:05:14 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-28 22:05:01 * @FilePath: /cesium-web-vue/src/components/mapInfo/mapInfo.ts */ import { throttle } from '@/utils/index'; import { Viewer, ScreenSpaceEventHandler, Cartesian2, ScreenSpaceEventType, EllipsoidGeodesic, Math as CMath } from 'cesium'; interface infos { lng: string, lat: string, height: string, ViewpointsHeight: string, scale: string } const computeMapScale = (viewer: Viewer, infos: infos) => { const canvas = viewer.canvas; const globe = viewer.scene.globe; // 窗口坐标(canvas.width/2, canvas.height - 1)和(canvas.width/2 + 1, canvas.height - 1) // 二者相隔距离仅为一个像素 const leftPixelPosition = new Cartesian2(canvas.width/2, canvas.height/2); const rightPixelPosition = new Cartesian2(canvas.width/2 + 1, canvas.height/2); viewer.scene.postRender.addEventListener(() => { const leftPixelRay = viewer.scene.camera.getPickRay(leftPixelPosition) const rightPixelRay = viewer.scene.camera.getPickRay(rightPixelPosition) if(!leftPixelRay || !rightPixelRay) { return; } // 两个像素点在globe上对应的Cartesian3坐标 const leftPixelCar3 = globe.pick(leftPixelRay, viewer.scene); const rightPixelCar3 = globe.pick(rightPixelRay, viewer.scene); if(!leftPixelCar3 || !rightPixelCar3) { return } const leftCartographic = globe.ellipsoid.cartesianToCartographic(leftPixelCar3); const rightCartographic = globe.ellipsoid.cartesianToCartographic(rightPixelCar3); const geodesic = new EllipsoidGeodesic(); // 椭球测地线 // 设置测地线的起点和终点 geodesic.setEndPoints(leftCartographic, rightCartographic); const pixelDistance = geodesic.surfaceDistance * 100 / 1000; if(pixelDistance < 1) { infos.scale = (pixelDistance * 1000).toFixed(2) + 'm' } else { infos.scale = pixelDistance.toFixed(2) + 'km' } }) } /** * @description: 实时拾取鼠标的坐标信息,并更新infos对象的内容 * @param {*} * @return {*} */ const pickMousePosition = (viewer: Viewer, infos: infos): any => { const handler3D = new ScreenSpaceEventHandler(viewer.scene.canvas); const handlerFunc = movement => { const pick = new Cartesian2(movement.endPosition.x, movement.endPosition.y); const pickRay = viewer.camera.getPickRay(pick); if (!pickRay) { return } const cartesian = viewer.scene.globe.pick(pickRay, viewer.scene); if (!cartesian) { return } const cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian); // 经纬度 const lat = CMath.toDegrees(cartographic.latitude); const lng = CMath.toDegrees(cartographic.longitude); // 海拔 const height = viewer.scene.globe.getHeight(cartographic); // 视点海拔高度 const ViewpointsHeight = viewer.scene.camera.positionCartographic.height; infos.lng = lng ? lng.toFixed(2) + '' : ''; infos.lat = lat ? lat.toFixed(2) + '' : ''; infos.height = height ? height.toFixed(2) + '' : ''; infos.ViewpointsHeight = ViewpointsHeight ? ViewpointsHeight.toFixed(2) + '' : ''; } handler3D.setInputAction(throttle(handlerFunc, 500), ScreenSpaceEventType.MOUSE_MOVE) } export { pickMousePosition, computeMapScale }
CN-3211/vt-cesium2.0
src/utils/vue-utils/transform/transform.ts
/* * @Date: 2021-06-10 09:13:02 * @LastEditors: huangzh873 * @LastEditTime: 2022-03-28 19:28:08 * @FilePath: /cesium-web-vue/src/utils/vue-utils/transform/transform.ts */ import * as Cesium from 'cesium' export default class transform { static boundingSphereCenter: Cesium.Cartesian3 constructor(boundingSphereCenter: Cesium.Cartesian3) { transform.boundingSphereCenter = boundingSphereCenter; } /** * @description: 平移 * @param {number} lng 目标经度 * @param {number} lat 目标维度 * @param {number} height 目标高度 * @return {Cesium.Matrix4} Matrix4矩阵 */ translation(lng:number, lat:number, height:number):Cesium.Matrix4 { const cartographic:Cesium.Cartographic = Cesium.Cartographic.fromCartesian( transform.boundingSphereCenter ); const surface:Cesium.Cartesian3 = Cesium.Cartesian3.fromRadians( cartographic.longitude, cartographic.latitude, cartographic.height ); const offset:Cesium.Cartesian3 = Cesium.Cartesian3.fromDegrees(lng, lat, height); const translation:Cesium.Cartesian3 = Cesium.Cartesian3.subtract( offset, surface, new Cesium.Cartesian3() ); // 最终的平移矩阵 return Cesium.Matrix4.fromTranslation( translation, new Cesium.Matrix4() ); } /** * @description: 旋转 * @param {number} xAngle 右手坐标系的x, y, z坐标 * @param {number} yAngle * @param {number} zAngle * @return {Cesium.Matrix4} 变换后的旋转矩阵 */ rotation(xAngle: number, yAngle:number, zAngle:number):Cesium.Matrix4 { const mx: Cesium.Matrix3 = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(xAngle)); const my: Cesium.Matrix3 = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(yAngle)); const mz: Cesium.Matrix3 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(zAngle)); const m: Cesium.Matrix3 = new Cesium.Matrix3(); Cesium.Matrix3.multiply(mx, my, m); Cesium.Matrix3.multiply(m, mz, m) return transform.handleTransform(m) } static handleTransform(rotateM3: Cesium.Matrix3) { const tmp = Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY); const tilesetMat: Cesium.Matrix4 = Cesium.Matrix4.fromArray(Cesium.Matrix4.toArray(tmp)); const tilesetMatRotation: Cesium.Matrix4 = Cesium.Matrix4.getMatrix3(tilesetMat, new Cesium.Matrix3()); const inverseTilesetMatRotation: Cesium.Matrix3 = Cesium.Matrix3.inverse(tilesetMatRotation, new Cesium.Matrix3()); const tilesetMatTranslation: Cesium.Cartesian3 = Cesium.Matrix4.getTranslation(tilesetMat, new Cesium.Cartesian3()) // 创建以tileset的中心为原点的坐标系 const originMat: Cesium.Matrix4 = Cesium.Transforms.eastNorthUpToFixedFrame(transform.boundingSphereCenter); const originMatRotation: Cesium.Matrix3 = Cesium.Matrix4.getMatrix3(originMat, new Cesium.Matrix3()); const originMatTranslation: Cesium.Cartesian3 = Cesium.Matrix4.getTranslation(originMat, new Cesium.Cartesian3()); const tilesetToOriginTranslation:Cesium.Matrix4 = Cesium.Matrix4.fromTranslation( // 为什么要subtract? // tileset减origin得到的矩阵能将模型负向移动origin的偏移量 Cesium.Cartesian3.subtract(tilesetMatTranslation, originMatTranslation, new Cesium.Cartesian3()) , new Cesium.Matrix4()); const tilesetToOriginRotation = Cesium.Matrix4.fromRotationTranslation( Cesium.Matrix3.inverse( Cesium.Matrix3.multiply(inverseTilesetMatRotation, originMatRotation, new Cesium.Matrix3()) , new Cesium.Matrix4()) ) const rotateM4:Cesium.Matrix4 = Cesium.Matrix4.fromRotationTranslation(rotateM3) // 转过去 Cesium.Matrix4.multiply(originMat, rotateM4, originMat); // 调整角度 Cesium.Matrix4.multiply(originMat, tilesetToOriginRotation, originMat); // 转回来 Cesium.Matrix4.multiply(originMat, tilesetToOriginTranslation, originMat); return originMat } }
CN-3211/vt-cesium2.0
src/store/modules/jt-cesium-vue/modules/cesium-data/state.ts
import type { JTPrimitiveState } from './modules/jt-primitive' export type CesiumDataStateAndModule = { notUsed: number jtPrimitive: JTPrimitiveState } export type State = { notUsed: number } export const defaultState = (): State => { return { notUsed: -1, } } export const state: State = defaultState()