Compare commits
4 Commits
12427efc7e
...
rtc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa938f7258 | ||
| 59aa904c5a | |||
|
|
06a87381d5 | ||
| 5444e25249 |
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useParams } from 'next/navigation';
|
import { useParams } from 'next/navigation';
|
||||||
import { socket } from '@/socket';
|
import useSocket from '@/hooks/useSocket';
|
||||||
|
import useRTC from '@/hooks/useRTC';
|
||||||
import { Eye } from 'lucide-react';
|
import { Eye } from 'lucide-react';
|
||||||
|
|
||||||
import Card from '@/components/Card';
|
import Card from '@/components/Card';
|
||||||
@@ -39,65 +40,20 @@ export default function GamePage() {
|
|||||||
const isDM = !!dmID;
|
const isDM = !!dmID;
|
||||||
const selectDeck: Deck | null = selectCard >= 0 ? cards[selectCard].deck : null;
|
const selectDeck: Deck | null = selectCard >= 0 ? cards[selectCard].deck : null;
|
||||||
|
|
||||||
|
const socket = useSocket({ gameID, setGameData, setNoGame });
|
||||||
|
const rtc = useRTC(socket);
|
||||||
|
console.log('useRTC:', rtc);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (gameIDParam) {
|
if (gameIDParam) {
|
||||||
setGameID(Array.isArray(gameIDParam) ? gameIDParam[0] : gameIDParam);
|
setGameID(Array.isArray(gameIDParam) ? gameIDParam[0] : gameIDParam);
|
||||||
}
|
}
|
||||||
}, [gameIDParam]);
|
}, [gameIDParam]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (gameID) {
|
|
||||||
socket.emit('join', gameID);
|
|
||||||
|
|
||||||
socket.on('init', (data: GameUpdate) => {
|
|
||||||
setGameData(data);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on('game-update', (data: GameUpdate) => {
|
|
||||||
setGameData(data);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on('join-error', (error) => {
|
|
||||||
console.error('Error:', error);
|
|
||||||
setNoGame(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on('flip-error', (error) => {
|
|
||||||
console.error('Error:', error);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
socket.removeAllListeners();
|
|
||||||
};
|
|
||||||
}, [gameID]);
|
|
||||||
|
|
||||||
const flipCard = (cardIndex: number) => {
|
|
||||||
socket.emit('flip-card', {
|
|
||||||
gameID,
|
|
||||||
cardIndex,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const redraw = (cardIndex: number) => {
|
|
||||||
socket.emit('redraw', {
|
|
||||||
gameID,
|
|
||||||
cardIndex,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const select = (cardIndex: number, cardID: string) => {
|
const select = (cardIndex: number, cardID: string) => {
|
||||||
setSelectCard(-1);
|
setSelectCard(-1);
|
||||||
|
|
||||||
socket.emit('select', {
|
socket.select(cardIndex, cardID);
|
||||||
gameID,
|
|
||||||
cardIndex,
|
|
||||||
cardID,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSettings = (gameData: GameUpdate) => {
|
|
||||||
socket.emit('settings', { gameID, gameData });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// map our five Tarokka cards to their proper locations in a 3x3 grid
|
// map our five Tarokka cards to their proper locations in a 3x3 grid
|
||||||
@@ -119,7 +75,7 @@ export default function GamePage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isDM && <Settings gameData={gameData} changeAction={handleSettings} />}
|
{isDM && <Settings gameData={gameData} changeAction={socket.handleSettings} />}
|
||||||
<div className="grid grid-cols-3 grid-rows-3 gap-8 w-fit mx-auto">
|
<div className="grid grid-cols-3 grid-rows-3 gap-8 w-fit mx-auto">
|
||||||
{Array.from({ length: 9 })
|
{Array.from({ length: 9 })
|
||||||
.map(arrangeCards)
|
.map(arrangeCards)
|
||||||
@@ -131,8 +87,8 @@ export default function GamePage() {
|
|||||||
card={card}
|
card={card}
|
||||||
position={layout[cardMap[index]]}
|
position={layout[cardMap[index]]}
|
||||||
settings={settings}
|
settings={settings}
|
||||||
flipAction={() => flipCard(cardMap[index])}
|
flipAction={() => socket.flipCard(cardMap[index])}
|
||||||
redrawAction={() => redraw(cardMap[index])}
|
redrawAction={() => socket.redraw(cardMap[index])}
|
||||||
selectAction={() => setSelectCard(cardMap[index])}
|
selectAction={() => setSelectCard(cardMap[index])}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -141,9 +97,10 @@ export default function GamePage() {
|
|||||||
</div>
|
</div>
|
||||||
<Notes gameData={gameData} show={cards.every(({ flipped }) => flipped)} />
|
<Notes gameData={gameData} show={cards.every(({ flipped }) => flipped)} />
|
||||||
<CardSelect
|
<CardSelect
|
||||||
closeAction={() => setSelectCard(-1)}
|
|
||||||
settings={settings}
|
|
||||||
show={selectDeck}
|
show={selectDeck}
|
||||||
|
hand={cards}
|
||||||
|
settings={settings}
|
||||||
|
closeAction={() => setSelectCard(-1)}
|
||||||
selectAction={(cardID) => select(selectCard, cardID)}
|
selectAction={(cardID) => select(selectCard, cardID)}
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import TiltCard from '@/components/TiltCard';
|
||||||
import ToolTip from '@/components/ToolTip';
|
import ToolTip from '@/components/ToolTip';
|
||||||
import StackTheDeck from '@/components/StackTheDeck';
|
import StackTheDeck from '@/components/StackTheDeck';
|
||||||
import tarokkaCards from '@/constants/tarokkaCards';
|
import tarokkaCards from '@/constants/tarokkaCards';
|
||||||
@@ -57,8 +58,8 @@ export default function Card({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<ToolTip content={tooltip || getTooltip()}>
|
<ToolTip content={tooltip || getTooltip()}>
|
||||||
<div
|
<TiltCard
|
||||||
className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10 ${dm ? 'cursor-pointer' : ''} `}
|
className={`h-[21vh] w-[15vh] relative perspective transition-transform duration-200 z-0 hover:z-10 hover:scale-150 ${dm ? 'cursor-pointer' : ''} `}
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
@@ -96,7 +97,7 @@ export default function Card({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</TiltCard>
|
||||||
</ToolTip>
|
</ToolTip>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import { CircleX } from 'lucide-react';
|
|||||||
import TarokkaDeck from '@/lib/TarokkaDeck';
|
import TarokkaDeck from '@/lib/TarokkaDeck';
|
||||||
import getURL from '@/tools/getURL';
|
import getURL from '@/tools/getURL';
|
||||||
|
|
||||||
import { Deck, Settings } from '@/types';
|
import { Deck, Settings, TarokkaGameCard } from '@/types';
|
||||||
|
|
||||||
const tarokkaDeck = new TarokkaDeck();
|
const tarokkaDeck = new TarokkaDeck();
|
||||||
|
|
||||||
type CardSelectProps = {
|
type CardSelectProps = {
|
||||||
closeAction: () => void;
|
closeAction: () => void;
|
||||||
selectAction: (cardID: string) => void;
|
selectAction: (cardID: string) => void;
|
||||||
|
hand: TarokkaGameCard[];
|
||||||
settings: Settings;
|
settings: Settings;
|
||||||
show: Deck | null;
|
show: Deck | null;
|
||||||
className?: string;
|
className?: string;
|
||||||
@@ -19,10 +20,13 @@ type CardSelectProps = {
|
|||||||
export default function CardSelect({
|
export default function CardSelect({
|
||||||
closeAction,
|
closeAction,
|
||||||
selectAction,
|
selectAction,
|
||||||
|
hand,
|
||||||
settings,
|
settings,
|
||||||
show,
|
show,
|
||||||
className = '',
|
className = '',
|
||||||
}: CardSelectProps) {
|
}: CardSelectProps) {
|
||||||
|
const handIDs = hand.map(({ id }) => id);
|
||||||
|
|
||||||
const handleClose = (event: React.MouseEvent<HTMLElement>) => {
|
const handleClose = (event: React.MouseEvent<HTMLElement>) => {
|
||||||
if (event.target === event.currentTarget) {
|
if (event.target === event.currentTarget) {
|
||||||
closeAction();
|
closeAction();
|
||||||
@@ -48,19 +52,21 @@ export default function CardSelect({
|
|||||||
onClick={handleClose}
|
onClick={handleClose}
|
||||||
className={`flex flex-wrap justify-center items-center gap-3 h-dvh w-2/3 overflow-scroll scrollbar-hide p-4`}
|
className={`flex flex-wrap justify-center items-center gap-3 h-dvh w-2/3 overflow-scroll scrollbar-hide p-4`}
|
||||||
>
|
>
|
||||||
{cards.map((card) => (
|
{cards
|
||||||
<div
|
.filter(({ id }) => !handIDs.includes(id))
|
||||||
key={card.id}
|
.map((card) => (
|
||||||
className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10`}
|
<div
|
||||||
onClick={() => selectAction(card.id)}
|
key={card.id}
|
||||||
>
|
className={`relative h-[21vh] w-[15vh] perspective transition-transform duration-200 hover:scale-150 z-0 hover:z-10`}
|
||||||
<img
|
onClick={() => selectAction(card.id)}
|
||||||
src={getURL(card, settings)}
|
>
|
||||||
alt={card.aria}
|
<img
|
||||||
className="rounded-lg border border-yellow-500/25 hover:drop-shadow-[0_0_3px_#ffd700/50]"
|
src={getURL(card, settings)}
|
||||||
/>
|
alt={card.aria}
|
||||||
</div>
|
className="rounded-lg border border-yellow-500/25 hover:drop-shadow-[0_0_3px_#ffd700/50]"
|
||||||
))}
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
48
components/TiltCard.tsx
Normal file
48
components/TiltCard.tsx
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { useRef } from 'react';
|
||||||
|
|
||||||
|
export default function TiltCard({
|
||||||
|
children,
|
||||||
|
className = '',
|
||||||
|
onClick = () => {},
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
className?: string;
|
||||||
|
onClick: (event: React.MouseEvent) => void;
|
||||||
|
}) {
|
||||||
|
const cardRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const handleMouseMove = (e: React.MouseEvent) => {
|
||||||
|
const card = cardRef.current;
|
||||||
|
if (!card) return;
|
||||||
|
|
||||||
|
const rect = card.getBoundingClientRect();
|
||||||
|
const x = e.clientX - rect.left;
|
||||||
|
const y = e.clientY - rect.top;
|
||||||
|
const centerX = rect.width / 2;
|
||||||
|
const centerY = rect.height / 2;
|
||||||
|
|
||||||
|
const rotateX = ((y - centerY) / centerY) * -20;
|
||||||
|
const rotateY = ((x - centerX) / centerX) * 20;
|
||||||
|
|
||||||
|
card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMouseLeave = () => {
|
||||||
|
const card = cardRef.current;
|
||||||
|
if (!card) return;
|
||||||
|
card.style.transform = `rotateX(0deg) rotateY(0deg)`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`${className}`}
|
||||||
|
onMouseMove={handleMouseMove}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<div ref={cardRef} className={`h-full w-full transition-transform duration-0`}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
95
hooks/useChatGPT.ts
Normal file
95
hooks/useChatGPT.ts
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { io, Socket } from 'socket.io-client';
|
||||||
|
|
||||||
|
interface CursorPosition {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PeerMouseHook {
|
||||||
|
cursors: Record<string, CursorPosition>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePeerMouse(roomId: string): PeerMouseHook {
|
||||||
|
const [cursors, setCursors] = useState<Record<string, CursorPosition>>({});
|
||||||
|
const socketRef = useRef<Socket | null>(null);
|
||||||
|
const peers = useRef<Record<string, RTCPeerConnection>>({});
|
||||||
|
const channels = useRef<Record<string, RTCDataChannel>>({});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const socket = io();
|
||||||
|
socketRef.current = socket;
|
||||||
|
|
||||||
|
socket.emit('join-room', roomId);
|
||||||
|
|
||||||
|
socket.on('new-peer', async (peerId: string) => {
|
||||||
|
const pc = createPeer(peerId, true);
|
||||||
|
const offer = await pc.createOffer();
|
||||||
|
await pc.setLocalDescription(offer);
|
||||||
|
socket.emit('signal', { to: peerId, data: { description: pc.localDescription } });
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('signal', async ({ from, data }) => {
|
||||||
|
const pc = peers.current[from] || createPeer(from, false);
|
||||||
|
|
||||||
|
if (data.description) {
|
||||||
|
await pc.setRemoteDescription(data.description);
|
||||||
|
|
||||||
|
if (data.description.type === 'offer') {
|
||||||
|
const answer = await pc.createAnswer();
|
||||||
|
await pc.setLocalDescription(answer);
|
||||||
|
socket.emit('signal', { to: from, data: { description: pc.localDescription } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.candidate) {
|
||||||
|
await pc.addIceCandidate(data.candidate);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function createPeer(peerId: string, isInitiator: boolean): RTCPeerConnection {
|
||||||
|
const pc = new RTCPeerConnection();
|
||||||
|
|
||||||
|
if (isInitiator) {
|
||||||
|
const channel = pc.createDataChannel('mouse');
|
||||||
|
setupChannel(peerId, channel);
|
||||||
|
} else {
|
||||||
|
pc.ondatachannel = (e) => setupChannel(peerId, e.channel);
|
||||||
|
}
|
||||||
|
|
||||||
|
pc.onicecandidate = (e) => {
|
||||||
|
if (e.candidate) {
|
||||||
|
socket.emit('signal', { to: peerId, data: { candidate: e.candidate } });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
peers.current[peerId] = pc;
|
||||||
|
return pc;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupChannel(peerId: string, channel: RTCDataChannel) {
|
||||||
|
channels.current[peerId] = channel;
|
||||||
|
channel.onmessage = (e) => {
|
||||||
|
const pos = JSON.parse(e.data);
|
||||||
|
setCursors((prev) => ({ ...prev, [peerId]: pos }));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMouseMove(e: MouseEvent) {
|
||||||
|
const pos = JSON.stringify({ x: e.clientX, y: e.clientY });
|
||||||
|
Object.values(channels.current).forEach((ch) => {
|
||||||
|
if (ch.readyState === 'open') ch.send(pos);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('mousemove', handleMouseMove);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('mousemove', handleMouseMove);
|
||||||
|
socket.disconnect();
|
||||||
|
Object.values(peers.current).forEach((pc) => pc.close());
|
||||||
|
};
|
||||||
|
}, [roomId]);
|
||||||
|
|
||||||
|
return { cursors };
|
||||||
|
}
|
||||||
54
hooks/useRTC.ts
Normal file
54
hooks/useRTC.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import RTCPeer from '@/lib/RTCPeer';
|
||||||
|
|
||||||
|
import type { UseSocket } from '@/hooks/useSocket';
|
||||||
|
|
||||||
|
import type {} from '@/types';
|
||||||
|
|
||||||
|
// interface UseSocketProps {
|
||||||
|
// gameID: string;
|
||||||
|
// setGameData: (gameUpdate: GameUpdate) => void;
|
||||||
|
// setNoGame: (noGame: boolean) => void;
|
||||||
|
// }
|
||||||
|
|
||||||
|
const channelName = 'tilt';
|
||||||
|
|
||||||
|
export default function useRTC({
|
||||||
|
ready,
|
||||||
|
registerAnsweredReceiver,
|
||||||
|
registerOfferredReceiver,
|
||||||
|
rtcAnswer: sendAnswer,
|
||||||
|
rtcOffer: sendOffer,
|
||||||
|
}: UseSocket) {
|
||||||
|
const [peers, setPeers] = useState<RTCPeer[]>([]);
|
||||||
|
|
||||||
|
const answerHandler = (answer: RTCSessionDescriptionInit) => {
|
||||||
|
console.log('[useRTC] answer received', answer);
|
||||||
|
console.log('[useRTC] peers:', peers.length);
|
||||||
|
const peer = peers[0];
|
||||||
|
console.log('peer:', peer);
|
||||||
|
peer.onAnswer(answer);
|
||||||
|
};
|
||||||
|
|
||||||
|
const offerHandler = (offer: RTCSessionDescriptionInit) => {
|
||||||
|
console.log('[useRTC] offer received', offer);
|
||||||
|
setPeers((peers) => {
|
||||||
|
peers.push(new RTCPeer({ channelName, offer, sendAnswer, sendOffer }));
|
||||||
|
return peers;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (ready) {
|
||||||
|
console.log('-=-= SETTING THINGS UP =-=-');
|
||||||
|
registerAnsweredReceiver(answerHandler);
|
||||||
|
registerOfferredReceiver(offerHandler);
|
||||||
|
|
||||||
|
setPeers([new RTCPeer({ channelName, sendAnswer, sendOffer })]);
|
||||||
|
}
|
||||||
|
}, [ready]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
count: peers.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
123
hooks/useSocket.ts
Normal file
123
hooks/useSocket.ts
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { socket } from '@/socket';
|
||||||
|
|
||||||
|
import type { GameUpdate } from '@/types';
|
||||||
|
|
||||||
|
export interface UseSocketProps {
|
||||||
|
gameID: string;
|
||||||
|
setGameData: (gameUpdate: GameUpdate) => void;
|
||||||
|
setNoGame: (noGame: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UseSocket {
|
||||||
|
ready: boolean;
|
||||||
|
flipCard: (cardIndex: number) => void;
|
||||||
|
handleSettings: (cardData: GameUpdate) => void;
|
||||||
|
redraw: (cardIndex: number) => void;
|
||||||
|
rtcAnswer: (answer: RTCSessionDescriptionInit) => void;
|
||||||
|
registerAnsweredReceiver: (receiver: (answer: RTCSessionDescriptionInit) => void) => void;
|
||||||
|
rtcOffer: (offer: RTCSessionDescriptionInit) => void;
|
||||||
|
registerOfferredReceiver: (receiver: (offer: RTCSessionDescriptionInit) => void) => void;
|
||||||
|
select: (cardIndex: number, cardID: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function useSocket({ gameID, setGameData, setNoGame }: UseSocketProps): UseSocket {
|
||||||
|
const [ready, setReady] = useState(false);
|
||||||
|
const answerRef = useRef<(answer: RTCSessionDescriptionInit) => void>(null);
|
||||||
|
const offerRef = useRef<(offer: RTCSessionDescriptionInit) => void>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (gameID) {
|
||||||
|
socket.emit('join', gameID);
|
||||||
|
|
||||||
|
socket.on('init', (data: GameUpdate) => {
|
||||||
|
setReady(true);
|
||||||
|
setGameData(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('game-update', (data: GameUpdate) => {
|
||||||
|
setGameData(data);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('join-error', (error) => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
setNoGame(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('flip-error', (error) => {
|
||||||
|
console.error('Error:', error);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('rtc-answered', (answered: RTCSessionDescriptionInit) => {
|
||||||
|
if (answerRef.current) answerRef.current(answered);
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('rtc-offered', (offered: RTCSessionDescriptionInit) => {
|
||||||
|
if (offerRef.current) {
|
||||||
|
offerRef.current(offered);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socket.removeAllListeners();
|
||||||
|
};
|
||||||
|
}, [gameID]);
|
||||||
|
|
||||||
|
const flipCard = (cardIndex: number) => {
|
||||||
|
console.log('flip-card', {
|
||||||
|
gameID,
|
||||||
|
cardIndex,
|
||||||
|
});
|
||||||
|
socket.emit('flip-card', {
|
||||||
|
gameID,
|
||||||
|
cardIndex,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSettings = (gameData: GameUpdate) => {
|
||||||
|
socket.emit('settings', {
|
||||||
|
gameID,
|
||||||
|
gameData,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const redraw = (cardIndex: number) => {
|
||||||
|
socket.emit('redraw', {
|
||||||
|
gameID,
|
||||||
|
cardIndex,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const rtcAnswer = (answer: RTCSessionDescriptionInit) => {
|
||||||
|
console.log('rtc-answer', { gameID, answer });
|
||||||
|
socket.emit('rtc-answer', { gameID, answer });
|
||||||
|
};
|
||||||
|
|
||||||
|
const rtcOffer = (offer: RTCSessionDescriptionInit) => {
|
||||||
|
console.log('rtc-offer', { gameID, offer });
|
||||||
|
socket.emit('rtc-offer', { gameID, offer });
|
||||||
|
};
|
||||||
|
|
||||||
|
const select = (cardIndex: number, cardID: string) => {
|
||||||
|
socket.emit('select', {
|
||||||
|
gameID,
|
||||||
|
cardIndex,
|
||||||
|
cardID,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
ready,
|
||||||
|
flipCard,
|
||||||
|
handleSettings,
|
||||||
|
redraw,
|
||||||
|
rtcAnswer,
|
||||||
|
registerAnsweredReceiver: (receiver: (obj: RTCSessionDescriptionInit) => void[]) =>
|
||||||
|
(answerRef.current = receiver),
|
||||||
|
rtcOffer,
|
||||||
|
registerOfferredReceiver: (receiver: (obj: RTCSessionDescriptionInit) => void[]) =>
|
||||||
|
(offerRef.current = receiver),
|
||||||
|
select,
|
||||||
|
};
|
||||||
|
}
|
||||||
131
lib/RTCPeer.ts
Normal file
131
lib/RTCPeer.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
const servers = {
|
||||||
|
iceServers: [
|
||||||
|
{ url: 'stun:stun01.sipphone.com' },
|
||||||
|
{ url: 'stun:stun.ekiga.net' },
|
||||||
|
{ url: 'stun:stun.fwdnet.net' },
|
||||||
|
{ url: 'stun:stun.ideasip.com' },
|
||||||
|
{ url: 'stun:stun.iptel.org' },
|
||||||
|
{ url: 'stun:stun.rixtelecom.se' },
|
||||||
|
{ url: 'stun:stun.schlund.de' },
|
||||||
|
{ url: 'stun:stun.l.google.com:19302' },
|
||||||
|
{ url: 'stun:stun1.l.google.com:19302' },
|
||||||
|
{ url: 'stun:stun2.l.google.com:19302' },
|
||||||
|
{ url: 'stun:stun3.l.google.com:19302' },
|
||||||
|
{ url: 'stun:stun4.l.google.com:19302' },
|
||||||
|
{ url: 'stun:stunserver.org' },
|
||||||
|
{ url: 'stun:stun.softjoys.com' },
|
||||||
|
{ url: 'stun:stun.voiparound.com' },
|
||||||
|
{ url: 'stun:stun.voipbuster.com' },
|
||||||
|
{ url: 'stun:stun.voipstunt.com' },
|
||||||
|
{ url: 'stun:stun.voxgratia.org' },
|
||||||
|
{ url: 'stun:stun.xten.com' },
|
||||||
|
|
||||||
|
// {
|
||||||
|
// url: 'turn:numb.viagenie.ca',
|
||||||
|
// credential: 'muazkh',
|
||||||
|
// username: 'webrtc@live.com',
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// url: 'turn:192.158.29.39:3478?transport=udp',
|
||||||
|
// credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
|
||||||
|
// username: '28224511:1379330808',
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// url: 'turn:192.158.29.39:3478?transport=tcp',
|
||||||
|
// credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
|
||||||
|
// username: '28224511:1379330808',
|
||||||
|
// },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const pcConstraints = {
|
||||||
|
optional: [{ DtlsSrtpKeyAgreement: true }],
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface RTCPeerProps {
|
||||||
|
channelName: string;
|
||||||
|
offer?: RTCSessionDescriptionInit;
|
||||||
|
sendAnswer: (offer: RTCSessionDescriptionInit) => void;
|
||||||
|
sendOffer: (offer: RTCSessionDescriptionInit) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class RTCPeer {
|
||||||
|
channelName: string;
|
||||||
|
peerConnection: RTCPeerConnection;
|
||||||
|
channel: RTCDataChannel;
|
||||||
|
|
||||||
|
sendAnswer: (offer: RTCSessionDescriptionInit) => void;
|
||||||
|
sendOffer: (offer: RTCSessionDescriptionInit) => void;
|
||||||
|
|
||||||
|
constructor({ channelName, offer, sendAnswer, sendOffer }: RTCPeerProps) {
|
||||||
|
this.sendOffer = sendOffer;
|
||||||
|
this.sendAnswer = sendAnswer;
|
||||||
|
this.channelName = channelName;
|
||||||
|
|
||||||
|
this.peerConnection = new RTCPeerConnection(); //(servers, pcConstraints);
|
||||||
|
this.peerConnection.onicecandidate = offer
|
||||||
|
? this.#handleIceCandidateAnswer
|
||||||
|
: this.#handleIceCandidateOffer;
|
||||||
|
|
||||||
|
this.#createDataChannel();
|
||||||
|
|
||||||
|
if (offer) {
|
||||||
|
console.log('answer');
|
||||||
|
this.peerConnection.setRemoteDescription(offer);
|
||||||
|
this.peerConnection.createAnswer().then((answer) => {
|
||||||
|
this.peerConnection.setLocalDescription(answer);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log('call');
|
||||||
|
this.peerConnection.createOffer().then((offer) => {
|
||||||
|
this.peerConnection.setLocalDescription(offer);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onAnswer = (answer: RTCSessionDescriptionInit) => {
|
||||||
|
this.peerConnection.setRemoteDescription(answer);
|
||||||
|
};
|
||||||
|
|
||||||
|
#handleIceCandidateAnswer = (event: RTCPeerConnectionIceEvent) => {
|
||||||
|
if (!event.candidate) {
|
||||||
|
const answer = this.peerConnection.localDescription;
|
||||||
|
|
||||||
|
console.log('send-answer', { answer });
|
||||||
|
if (answer) {
|
||||||
|
this.sendAnswer(answer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
#handleIceCandidateOffer = (event: RTCPeerConnectionIceEvent) => {
|
||||||
|
if (!event.candidate) {
|
||||||
|
const offer = this.peerConnection.localDescription;
|
||||||
|
|
||||||
|
if (offer) {
|
||||||
|
console.log('send-offer', { offer });
|
||||||
|
this.sendOffer(offer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
#createDataChannel = () => {
|
||||||
|
try {
|
||||||
|
this.channel = this.peerConnection.createDataChannel(this.channelName);
|
||||||
|
|
||||||
|
this.channel.onopen = () => {
|
||||||
|
console.log('Receive Channel[onopen]:', this.channel.readyState);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.channel.onmessage = (event: MessageEvent) => {
|
||||||
|
console.log('Receive Channel[onmessage]:', event.data);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.channel.onclose = () => {
|
||||||
|
console.log('Receive Channel[onclose]:', this.channel.readyState);
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[RTCPeer|#createDataChannel] ERROR', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
26
server.ts
26
server.ts
@@ -119,6 +119,32 @@ app.prepare().then(() => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
socket.on('rtc-answer', ({ gameID, answer }: { gameID: string; answer: any }) => {
|
||||||
|
try {
|
||||||
|
const gameState = gameStore.getGame(gameID);
|
||||||
|
console.log('[rtc-answer]', gameID);
|
||||||
|
|
||||||
|
io.to(gameState.dmID).emit('rtc-answered', answer);
|
||||||
|
io.to(gameState.spectatorID).emit('rtc-answered', answer);
|
||||||
|
} catch (e) {
|
||||||
|
const error = e instanceof Error ? e.message : e;
|
||||||
|
console.error(Date.now(), 'Error[rtc-answer]', error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('rtc-offer', ({ gameID, offer }: { gameID: string; offer: any }) => {
|
||||||
|
try {
|
||||||
|
const gameState = gameStore.getGame(gameID);
|
||||||
|
console.log('[rtc-offer]', gameID);
|
||||||
|
|
||||||
|
io.to(gameState.dmID).emit('rtc-offered', offer);
|
||||||
|
io.to(gameState.spectatorID).emit('rtc-offered', offer);
|
||||||
|
} catch (e) {
|
||||||
|
const error = e instanceof Error ? e.message : e;
|
||||||
|
console.error(Date.now(), 'Error[rtc-offer]', error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
socket.on('disconnect', () => {
|
socket.on('disconnect', () => {
|
||||||
try {
|
try {
|
||||||
const game = gameStore.playerExit(socket.id);
|
const game = gameStore.playerExit(socket.id);
|
||||||
|
|||||||
Reference in New Issue
Block a user