### Install Alt1lib using npm Source: https://github.com/skillbert/alt1/blob/master/docs/base.md This command installs the Alt1 library using npm, making it available for use in your project. Ensure you have Node.js and npm installed. ```sh npm install alt1 ``` -------------------------------- ### RuneScape Overlay Application using Alt1 Toolkit (TypeScript) Source: https://context7.com/skillbert/alt1/llms.txt A comprehensive TypeScript example demonstrating the Alt1 toolkit's functionality for building RuneScape overlay applications. It initializes various readers, captures game interface areas, and processes data for abilities, chat messages, dialogs, and buffs in a timed loop. Dependencies include the 'alt1/base', 'alt1/ability', 'alt1/chatbox', 'alt1/dialog', and 'alt1/buffs' modules. ```typescript import * as a1lib from "alt1/base"; import { AbilityReader } from "alt1/ability"; import ChatBoxReader from "alt1/chatbox"; import DialogReader from "alt1/dialog"; import BuffReader from "alt1/buffs"; // Initialize all readers const abilityReader = new AbilityReader([ { id: "sunshine", icon: await a1lib.imageDataFromUrl("./abilities/sunshine.png"), cooldown: 60 }, { id: "death_swiftness", icon: await a1lib.imageDataFromUrl("./abilities/death_swiftness.png"), cooldown: 60 } ]); const chatReader = new ChatBoxReader(); const dialogReader = new DialogReader(); const buffReader = new BuffReader(); // Find all interfaces abilityReader.find(); chatReader.find(); dialogReader.find(); buffReader.find(); // Main game loop setInterval(async () => { // Capture all areas efficiently const areas = { abilities: abilityReader.captureRect, chat: chatReader.pos?.mainbox.rect, dialog: dialogReader.pos, buffs: buffReader.pos }; const captures = await a1lib.captureMultiAsync(areas); // Read abilities and life stats if (captures.abilities && abilityReader.captureRect) { const capts = { bar0: captures.abilities }; const captAreas = { bar0: abilityReader.captureRect }; abilityReader.readAllSlotsInner(capts, captAreas); const life = abilityReader.readLife(captures.abilities, 0, 0); if (life.hp < 0.5) { console.log("Warning: Low HP!"); } // Check cooldowns for (const ability of abilityReader.mainbarAbilities()) { if (ability.ability?.id === "sunshine" && ability.cooldown === 0) { console.log("Sunshine ready!"); } } } // Read chat messages if (captures.chat) { const newLines = chatReader.read(); if (newLines) { newLines.forEach(line => { if (line.text.includes("drop")) { console.log(`Drop detected: ${line.text}`); } }); } } // Read dialog if (captures.dialog) { const dialog = dialogReader.read(); if (dialog?.opts) { console.log("Dialog options:", dialog.opts.map(o => o.text)); } } // Read buffs if (captures.buffs) { const buffs = buffReader.read(captures.buffs); console.log(`Active buffs: ${buffs.length}`); } }, 600); // Run every game tick ``` -------------------------------- ### Create Custom Fonts - TypeScript Source: https://context7.com/skillbert/alt1/llms.txt Allows the creation of custom font definitions by providing a template image and metadata. The metadata specifies character properties, colors, and spacing. The generated font can then be used with Alt1's OCR functions for reading text that doesn't match standard fonts. Includes options for visual debugging and an example of using the custom font. ```typescript import * as OCR from "alt1/ocr"; import * as a1lib from "alt1/base"; // Font metadata const fontMeta: OCR.GenerateFontMeta = { basey: 7, spacewidth: 3, threshold: 0.6, color: [255, 255, 255], shadow: false, chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", seconds: ".", bonus: { "n": 50, "r": -30 }, unblendmode: "removebg" }; // Load font template image const templateImg = await a1lib.imageDataFromUrl("./font-template.png"); // Generate font definition const font = OCR.loadFontImage(templateImg, fontMeta); // Debug font visually OCR.debugFont(font); // Use the font const text = OCR.readLine(capturedImg, font, [[255, 255, 255]], 0, 10, true); console.log(`Read: ${text.text}`); ``` -------------------------------- ### Load and Display Image Data using Alt1 ImageData Loader Source: https://github.com/skillbert/alt1/blob/master/docs/imagedata-loader.md This JavaScript code demonstrates how to import and use the Alt1 ImageData Loader in an application. It first imports necessary base functionality and then loads a '.data.png' file, displaying the loaded image data using the 'show()' method. ```javascript //required for ImageData.prototype.show and also used by the client sided part of the loader import "alt1/base"; require("./img.data.png").then(buffer=>{ buffer.show(); }) ``` -------------------------------- ### Loading Image Data with Alt1 Base Module Source: https://context7.com/skillbert/alt1/llms.txt Provides methods to load image data from various sources including URLs, Base64 strings, and file buffers. Includes a utility to check for and clear PNG colorspace data. ```typescript import * as a1lib from "alt1/base"; // Load from URL with colorspace correction const img1 = await a1lib.imageDataFromUrl("https://example.com/icon.png"); // Load from base64 const img2 = await a1lib.imageDataFromBase64("iVBORw0KGg..."); // Load from file buffer const response = await fetch("./image.png"); const buffer = new Uint8Array(await response.arrayBuffer()); const img3 = await a1lib.imageDataFromFileBuffer(buffer); // Clear PNG colorspace data for consistency if (a1lib.isPngBuffer(buffer)) { a1lib.clearPngColorspace(buffer); } ``` -------------------------------- ### Screen Capture with Alt1 Base Module Source: https://context7.com/skillbert/alt1/llms.txt Captures screen regions synchronously or asynchronously. Supports capturing multiple areas and holding images in memory for faster operations. It can also capture the full RuneScape window. ```typescript import * as a1lib from "alt1/base"; // Synchronous capture - simple but blocking const img = a1lib.capture(100, 100, 500, 400); console.log(img.width, img.height); // 500, 400 // Asynchronous capture - better performance const imgAsync = await a1lib.captureAsync(100, 100, 500, 400); // Capture multiple areas in a single frame const areas = { chatbox: { x: 10, y: 600, width: 500, height: 300 }, abilities: { x: 600, y: 900, width: 400, height: 50 }, minimap: { x: 1700, y: 50, width: 200, height: 200 } }; const captures = await a1lib.captureMultiAsync(areas); console.log(captures.chatbox.width); // 500 console.log(captures.abilities.height); // 50 // Hold image in Alt1 memory for fast operations const imgRef = a1lib.captureHold(0, 0, 1920, 1080); const matches = imgRef.findSubimage(needleImg); console.log(`Found ${matches.length} matches`); // Capture full RuneScape window const fullScreen = a1lib.captureHoldFullRs(); ``` -------------------------------- ### Track Tooltips with alt1 Source: https://context7.com/skillbert/alt1/llms.txt Enables real-time tracking of tooltips on the screen using the 'alt1/tooltip' library. The provided callback function receives tooltip data, including position and size, and can be configured to run at a specified interval (100ms). It also demonstrates how to stop tracking and perform a one-time read. ```typescript import TooltipReader from "alt1/tooltip"; const reader = new TooltipReader(); // Start tracking tooltips reader.track((tooltip) => { if (tooltip) { console.log("Tooltip detected:"); console.log(` Position: (${tooltip.x}, ${tooltip.y})`); console.log(` Size: ${tooltip.width}x${tooltip.height}`); // Additional tooltip data available depending on type } else { console.log("No tooltip visible"); } }, 100); // Check every 100ms // Stop tracking setTimeout(() => { reader.stopTrack(); }, 60000); // Stop after 1 minute // One-time tooltip read const tooltip = TooltipReader.read(); if (tooltip) { console.log(`Tooltip at (${tooltip.x}, ${tooltip.y})`); } ``` -------------------------------- ### Handling Pasted Images and Drag & Drop with Alt1 (TypeScript) Source: https://context7.com/skillbert/alt1/llms.txt This snippet demonstrates how to use the Alt1 library to handle image pasting and drag & drop events. It includes setting up a listener for paste events, converting the pasted image reference to ImageData for processing, and handling potential errors. It also shows how to trigger a file dialog programmatically. Dependencies include 'alt1/base/pasteinput' and 'alt1/base'. ```typescript import * as PasteInput from "alt1/base/pasteinput"; import * as a1lib from "alt1/base"; // Listen for paste events PasteInput.listen( (imgref) => { console.log(`Image pasted: ${imgref.width}x${imgref.height}`); // Convert to ImageData for processing const img = imgref.toData(); // Process the image const [r, g, b, a] = img.getPixel(0, 0); console.log(`First pixel: rgba(${r}, ${g}, ${b}, ${a})`); }, (error, errorCode) => { console.error(`Paste error: ${error} (code: ${errorCode})`); }, true // Enable drag & drop ); // Programmatic file dialog document.getElementById("uploadBtn")?.addEventListener("click", () => { PasteInput.fileDialog(); }); ``` -------------------------------- ### Capture and Display Game Image using Alt1lib Source: https://github.com/skillbert/alt1/blob/master/docs/base.md This JavaScript code demonstrates how to capture a specified region of the game area using `a1lib.capture` and then display the captured image. It returns an image reference and converts it to a data buffer for display. ```js import * as a1lib from "alt1/base"; // Captures a 400x400 rectangle starting at position 100,100 from the top-left of the game area // imgref now contains a reference to the image (in this case still in Alt1 memory) var imgref = a1lib.capture(100,100,400,400); // Retrieve our raw pixel data so we can directly read it var imagebuffer = imgref.toData(); // Show the image by adding it to the DOM (for debugging) imagebuffer.show(); ``` -------------------------------- ### Matching Specific Buffs with Alt1 BuffReader (TypeScript) Source: https://context7.com/skillbert/alt1/llms.txt This snippet demonstrates how to use the Alt1 BuffReader to find and identify specific buffs in the game. It covers loading buff icons, capturing the relevant screen area, reading buff data, and checking for specific buffs by matching their icons or comparing pixel data. Dependencies include 'alt1/buffs' and 'alt1/base'. ```typescript import BuffReader from "alt1/buffs"; import * as a1lib from "alt1/base"; const reader = new BuffReader(); // Load known buff icons const overloadIcon = await a1lib.imageDataFromUrl("./buffs/overload.png"); const prayerIcon = await a1lib.imageDataFromUrl("./buffs/prayer.png"); if (reader.find()) { const img = a1lib.capture(reader.pos.x, reader.pos.y, 400, 60); const buffs = reader.read(img); // Check for specific buff const overloadBuff = BuffReader.matchBuff(buffs, overloadIcon); if (overloadBuff) { const timeLeft = overloadBuff.readTime(); console.log(`Overload active: ${timeLeft}s remaining`); } // Compare buff manually buffs.forEach(buff => { const matches = buff.compareBuffer(prayerIcon); if (matches) { console.log("Prayer buff active"); } // Count matching pixels for partial match const matchCount = buff.countMatch(prayerIcon, true); console.log(`Match confidence: ${matchCount} pixels`); }); } ``` -------------------------------- ### Monitor Abilities Over Time with Alt1 Source: https://context7.com/skillbert/alt1/llms.txt Monitors abilities for readiness and cooldowns by periodically capturing the action bar. It sets up a hook to log when ability bars become visible and checks for specific abilities becoming available. This function runs every game tick (600ms). ```typescript import { AbilityReader } from "alt1/ability"; import * as a1lib from "alt1/base"; const reader = new AbilityReader(abilities); reader.find(); // Set up hook for when occluded bars become visible reader.hooks.onbarshown = (bar) => { console.log(`Bar ${bar.name} is now visible`); }; // Monitor abilities every game tick (600ms) setInterval(async () => { if (!reader.captureRect) return; const img = await a1lib.captureAsync( reader.captureRect.x, reader.captureRect.y, reader.captureRect.width, reader.captureRect.height ); const capts = { bar0: img }; const areas = { bar0: reader.captureRect }; reader.readAllSlotsInner(capts, areas); // Check for specific abilities ready for (const ability of reader.allAbilities()) { if (ability.ability?.id === "sunshine" && ability.cooldown === 0 && ability.available) { console.log("Sunshine is ready!"); } } }, 600); ``` -------------------------------- ### Image Detection and Comparison with Alt1 Base Source: https://context7.com/skillbert/alt1/llms.txt Performs subimage detection, pixel-level comparison, and matching against multiple image datasets. Includes utility for color mixing and unmixing. ```typescript import * as a1lib from "alt1/base"; import { ImageDetect } from "alt1/base"; // Find subimage locations const haystack = a1lib.captureHold(0, 0, 1920, 1080); const needle = await a1lib.imageDataFromUrl("./icon.data.png"); const locations = haystack.findSubimage(needle); locations.forEach(loc => { console.log(`Found at (${loc.x}, ${loc.y})`); }); // Compare two images and get difference score const img1 = a1lib.capture(100, 100, 50, 50); const img2 = a1lib.capture(200, 200, 50, 50); const diff = img1.pixelCompare(img2); console.log(`Difference: ${diff} pixels`); // Match against multiple possible images const icons = ImageDetect.ImageDataSet.fromFilmStrip( await a1lib.imageDataFromUrl("./icons.png"), 32 // width of each icon ); const result = icons.matchBest(capturedImg, 0, 0, 100); console.log(`Best match: index ${result.index}, score ${result.score}`); // Color mixing for detection const orangeColor = a1lib.mixColor(255, 128, 0); const [r, g, b] = a1lib.unmixColor(orangeColor); console.log(`RGB: ${r}, ${g}, ${b}`); ``` -------------------------------- ### Read Specific Chat Channels with Alt1 Source: https://context7.com/skillbert/alt1/llms.txt Demonstrates how to read from specific chat channels using Alt1's ChatBoxReader. It iterates through all detected chat windows, logging their type, timestamp status, position, and size. It then shows how to capture and read a specific line from the main chatbox. ```typescript import ChatBoxReader from "alt1/chatbox"; import * as a1lib from "alt1/base"; const reader = new ChatBoxReader(); const chatboxes = reader.find(); if (chatboxes) { // Iterate through all chat windows chatboxes.boxes.forEach((box, index) => { console.log(`Chatbox ${index}: `); console.log(` Type: ${box.type}`); // "main", "cc", "fc", "gc", "pc" console.log(` Has timestamp: ${box.timestamp}`); console.log(` Position: (${box.rect.x}, ${box.rect.y}) `); console.log(` Size: ${box.rect.width}x${box.rect.height} `); }); // Read from main chatbox const mainbox = chatboxes.mainbox; const img = a1lib.capture(mainbox.rect.x, mainbox.rect.y, mainbox.rect.width, mainbox.rect.height); // Read specific line const font = reader.readargs.font || fonts[0]; const line = reader.readChatLine(mainbox, img, 0, 0, font, reader.readargs.colors, 0); console.log(`Line 0: ${line.text}`); } ``` -------------------------------- ### Configure Webpack to Load .data.png Files with Alt1 ImageData Loader Source: https://github.com/skillbert/alt1/blob/master/docs/imagedata-loader.md This configuration snippet shows how to set up webpack to use the 'alt1/imagedata-loader' specifically for files ending with '.data.png'. Ensure this rule is placed after other PNG-related rules to maintain correct loading order. ```javascript module.exports={ ... module: { rules: [ ... // Make sure this rule comes after any other rules that affect .png files { test: /\.data\.png$/, loader: ['alt1/imagedata-loader'] } ] } } ``` -------------------------------- ### Configure Webpack for Alt1 Font Loader Source: https://github.com/skillbert/alt1/blob/master/docs/font-loader.md This webpack configuration demonstrates how to integrate the Alt1 Font Loader and the `alt1/imagedata-loader`. The `.fontmeta.json` files are processed by the font loader, while `.data.png` files are handled by the imagedata loader. Ensure the order of these rules is appropriate for your project to avoid conflicts with other loaders. ```javascript module.exports={ ... module: { rules: [ ... // Make sure this rule comes after any other rules that affect .png or .json files { test: /\.data\.png$/, loader: ['alt1/imagedata-loader'] }, { test: /\.fontmeta\.json$/, loader: ["alt1/font-loader"] } ] } } ``` -------------------------------- ### Read Dialog Components Separately with alt1 Source: https://context7.com/skillbert/alt1/llms.txt Allows reading specific components of a dialog box, such as the title, dialog text, or options, using the 'alt1/dialog' and 'alt1/base' libraries. It captures the game screen and then analyzes it for dialog or options, providing details like NPC name and option text. ```typescript import DialogReader from "alt1/dialog"; import * as a1lib from "alt1/base"; const reader = new DialogReader(); if (reader.find()) { const img = a1lib.captureHoldFullRs(); // Check if dialog (vs options) const isDialog = reader.checkDialog(img); console.log(`Is dialog: ${isDialog}`); // Read title only const title = reader.readTitle(img); console.log(`NPC: ${title}`); if (isDialog) { // Read dialog text const text = reader.readDialog(img, true); if (text) { console.log("Dialog:", text.join("\n")); } } else { // Find and read options const optionLocs = reader.findOptions(img); console.log(`Found ${optionLocs.length} options`); const options = reader.readOptions(img, optionLocs); if (options) { options.forEach(opt => { console.log(`Option: ${opt.text} (width: ${opt.width}px)`); }); } } } ``` -------------------------------- ### Read NPC Dialogs and Options with alt1 Source: https://context7.com/skillbert/alt1/llms.txt Finds and reads NPC dialog boxes, including title, text content, and selectable options. It requires the 'alt1/dialog' and 'alt1/base' libraries. The output includes dialog position, legacy mode status, title, text lines, and option details. ```typescript import DialogReader from "alt1/dialog"; import * as a1lib from "alt1/base"; const reader = new DialogReader(); // Find dialog box const dialogPos = reader.find(); if (dialogPos) { console.log(`Found dialog at (${dialogPos.x}, ${dialogPos.y})`); console.log(`Legacy mode: ${dialogPos.legacy}`); // Read dialog content const content = reader.read(); if (content) { console.log(`Title: ${content.title}`); // Check if it's dialog text or options if (content.text) { console.log("Dialog text:"); content.text.forEach(line => console.log(` ${line}`)); } if (content.opts) { console.log("Options:"); content.opts.forEach((opt, i) => { console.log(` ${i + 1}. ${opt.text}`); console.log(` Position: (${opt.x}, ${opt.y})`); console.log(` Hover: ${opt.hover}, Active: ${opt.active}`); }); } } } ``` -------------------------------- ### Webpack Loaders for Alt1 Assets (JavaScript) Source: https://context7.com/skillbert/alt1/llms.txt This snippet shows how to configure Webpack to load custom image and font assets for Alt1. The 'alt1/imagedata-loader' allows importing '.data.png' files as ImageData objects, while 'alt1/font-loader' processes '.fontmeta.json' files into FontDefinition objects. These loaders simplify asset integration into your project. ```javascript // webpack.config.js module.exports = { module: { rules: [ { test: /\.data\.png$/, use: "alt1/imagedata-loader" } ] } }; // Usage in TypeScript/JavaScript const icon = require("./icon.data.png"); // Returns: Promise icon.then(img => { console.log(`Loaded image: ${img.width}x${img.height}`); const [r, g, b, a] = img.getPixel(0, 0); console.log(`Top-left pixel: rgba(${r}, ${g}, ${b}, ${a})`); }); // With async/await async function loadIcon() { const img = await require("./ability-icon.data.png"); return img; } ``` ```javascript // webpack.config.js module.exports = { module: { rules: [ { test: /\.fontmeta\.json$/, use: "alt1/font-loader" } ] } }; // Font metadata file: custom_font.fontmeta.json { "basey": 8, "spacewidth": 4, "threshold": 0.7, "color": [255, 255, 255], "shadow": false, "chars": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "seconds": ". ,;:'\"!?()-", "bonus": { "i": 20, "l": 10, "n": -10 }, "unblendmode": "removebg" } // Usage const customFont = require("./custom_font.fontmeta.json"); // Returns: FontDefinition (ready to use) // Use immediately in OCR const text = OCR.readLine(buffer, customFont, [[255, 255, 255]], 0, 10, true); console.log(`Detected text: ${text.text}`); ``` -------------------------------- ### Find and Read Ability Bars - TypeScript Source: https://context7.com/skillbert/alt1/llms.txt Reads player abilities from ability bars on the screen. It requires defining abilities with their corresponding icon images and cooldowns. The `AbilityReader` class then finds these ability bars, reads the status of each ability (cooldown, availability, hotkey), and provides access to this information. ```typescript import { AbilityReader } from "alt1/ability"; import * as a1lib from "alt1/base"; // Define your abilities with icons const abilities = [ { id: "sunshine", icon: await a1lib.imageDataFromUrl("./abilities/sunshine.png"), cooldown: 60 }, { id: "tsunami", icon: await a1lib.imageDataFromUrl("./abilities/tsunami.png"), cooldown: 60 }, { id: "wild_magic", icon: await a1lib.imageDataFromUrl("./abilities/wild_magic.png"), cooldown: 20 } ]; const reader = new AbilityReader(abilities); // Find ability bars in the screenshot const barCount = reader.find(); if (barCount) { console.log(`Found ${barCount} ability bars`); // Read all abilities reader.readAllSlots(); // Access main bar abilities for (const ability of reader.mainbarAbilities()) { if (ability.ability) { console.log(`${ability.ability.id}`) console.log(` Cooldown: ${ability.cooldown}s`); console.log(` Available: ${ability.available}`); console.log(` Hotkey: ${ability.hotkey}`); console.log(` On GCD: ${ability.gcd}`); } } } ``` -------------------------------- ### Read Buffs and Debuffs with alt1 Source: https://context7.com/skillbert/alt1/llms.txt Reads and analyzes buffs and debuffs displayed on the buff bar using the 'alt1/buffs' and 'alt1/base' libraries. It finds the buff bar, captures the relevant area, and then iterates through each buff/debuff to read its status, time remaining, and specific arguments. ```typescript import BuffReader from "alt1/buffs"; import * as a1lib from "alt1/base"; const reader = new BuffReader(); // Find buff bar const found = reader.find(); if (found) { console.log("Found buff bar"); // Capture buff area const img = a1lib.capture(reader.pos.x, reader.pos.y, 400, 60); // Read all buffs const buffs = reader.read(img); console.log(`Found ${buffs.length} buffs/debuffs`); buffs.forEach((buff, index) => { console.log(`Buff ${index}:`); console.log(` Is debuff: ${buff.isdebuff}`); // Read time remaining const time = buff.readTime(); if (time > 0) { console.log(` Time: ${time}s`); } // Read buff arguments (varies by buff) const arg = buff.readArg("arg"); if (arg) { console.log(` Value: ${arg}`); } }); } ``` -------------------------------- ### Read Player Health, Prayer, and Stats with Alt1 Source: https://context7.com/skillbert/alt1/llms.txt Reads the player's current HP, Prayer, Summoning, and Adrenaline levels from the game interface using Alt1's AbilityReader. It can also read exact HP and Prayer values if available. Ensure the 'abilities' variable is properly initialized before use. ```typescript import { AbilityReader, ActionbarReader } from "alt1/ability"; import * as a1lib from "alt1/base"; const reader = new AbilityReader(abilities); reader.find(); const img = a1lib.capture(reader.captureRect.x, reader.captureRect.y, reader.captureRect.width, reader.captureRect.height); // Read life stats const life = reader.readLife(img, 0, 0); console.log(`HP: ${Math.round(life.hp * 100)}%`); console.log(`Prayer: ${Math.round(life.pray * 100)}%`); console.log(`Summoning: ${Math.round(life.sum * 100)}%`); console.log(`Adrenaline: ${Math.round(life.dren * 100)}%`); // Check exact values if available if (life.exacthp) { console.log(`Exact HP: ${life.exacthp.cur}/${life.exacthp.max}`); } if (life.exactpray) { console.log(`Exact Prayer: ${life.exactpray.cur}/${life.exactpray.max}`); } ``` -------------------------------- ### Read Chat Messages with Alt1 ChatBoxReader Source: https://context7.com/skillbert/alt1/llms.txt Reads messages from the game's chatbox using Alt1's ChatBoxReader. It finds chat windows, logs the number and type of chat windows found, and then reads new messages, iterating through their text and colored fragments. ```typescript import ChatBoxReader from "alt1/chatbox"; import * as a1lib from "alt1/base"; const reader = new ChatBoxReader(); // Find chatbox in the game const chatboxes = reader.find(); if (chatboxes) { console.log(`Found ${chatboxes.boxes.length} chat windows`); console.log(`Main chatbox type: ${chatboxes.mainbox.type}`); // Read new messages const newLines = reader.read(); if (newLines) { newLines.forEach(line => { console.log(`Message: ${line.text}`); // Process colored fragments line.fragments.forEach(frag => { const [r, g, b] = frag.color; console.log(` Fragment: "${frag.text}" color=(${r},${g},${b})`); }); }); } } ``` -------------------------------- ### Monitor Dialog Changes with alt1 Source: https://context7.com/skillbert/alt1/llms.txt Continuously monitors for changes in NPC dialog text and options using the 'alt1/dialog' library. It logs new dialog text and identifies options containing "yes". The function runs at a specified interval (600ms). ```typescript import DialogReader from "alt1/dialog"; import * as a1lib from "alt1/base"; const reader = new DialogReader(); let lastDialogText = ""; setInterval(() => { if (!reader.pos) { reader.find(); } if (reader.pos) { const content = reader.read(); if (content) { const currentText = content.text?.join(" ") || ""; // Check if dialog changed if (currentText !== lastDialogText && currentText) { console.log(`New dialog: ${currentText}`); lastDialogText = currentText; } // Handle options if (content.opts && content.opts.length > 0) { console.log(`Choose from ${content.opts.length} options`); content.opts.forEach(opt => { if (opt.text.toLowerCase().includes("yes")) { console.log(`"Yes" option at (${opt.x}, ${opt.y})`); } }); } } } }, 600); ``` -------------------------------- ### OCR Usage with Alt1 Library (JavaScript) Source: https://github.com/skillbert/alt1/blob/master/docs/ocr.md Demonstrates how to use the Alt1 OCR library in JavaScript to capture a screen area, load a font definition, and read text from the captured image. It requires the `alt1/ocr` and `alt1/base` modules, along with a font file. The function `findReadLine` returns the recognized text and a debug area. ```javascript import * as OCR from "alt1/ocr"; import * as A1lib from "alt1/base"; //load one of the packaged fonts import font from "alt1/fonts/aa_8px_mono.js"; //capture a 400x400 area of the screen starting at 100,100 var imgref = A1lib.capture(100,100,400,400); //grab the raw pixels var imagebuffer = imgref.toData(); var color = [255,255,255];//rgb => pure white //read the text at position 100,100 of the imagebuffer. The given point must be somewhere _in the middle_ of the text. var text = OCR.findReadLine(imagebuffer,font,[color],100,100); console.log(text)//{text:"hello",debugArea:{x:80,y:95,w:30,h:10}} ``` -------------------------------- ### ImageData Object Extensions in Alt1 Base Source: https://context7.com/skillbert/alt1/llms.txt Extends the ImageData object with methods for pixel manipulation, cloning regions, displaying images in the DOM, exporting to various formats (PNG bytes, Base64), and copying image data. ```typescript import * as a1lib from "alt1/base"; const img = a1lib.capture(100, 100, 200, 150); // Pixel operations const [r, g, b, a] = img.getPixel(50, 75); console.log(`Color at (50, 75): rgba(${r}, ${g}, ${b}, ${a})`); img.setPixel(50, 75, [255, 0, 0, 255]); // Clone region const cropped = img.clone({ x: 10, y: 10, width: 50, height: 50 }); // Display in DOM for debugging img.show(100, 100, 2); // x, y, zoom // Export to file const pngBytes = await img.toFileBytes("image/png", 0.9); const base64 = img.toPngBase64(); // Copy to another image const target = new ImageData(300, 300); img.copyTo(target, 0, 0, img.width, img.height, 50, 50); ``` -------------------------------- ### Customize Chat Detection with Alt1 Source: https://context7.com/skillbert/alt1/llms.txt Allows customization of Alt1's ChatBoxReader for more specific message detection. This includes adding custom colors to be recognized and configuring differential reading to only process new messages, optionally using timestamps for accuracy. It also sets a minimum overlap for comparison. ```typescript import ChatBoxReader, { defaultcolors } from "alt1/chatbox"; import * as a1lib from "alt1/base"; const reader = new ChatBoxReader(); // Add custom colors const customColor = a1lib.mixColor(200, 100, 50); reader.readargs.colors.push(customColor); // Configure diff reading reader.diffRead = true; // Only return new lines reader.diffReadUseTimestamps = true; // Use timestamps for diffing reader.minoverlap = 2; // Minimum lines to overlap for comparison // Find and monitor chat if (reader.find()) { setInterval(() => { const lines = reader.read(); if (lines) { lines.forEach(line => { // Check for specific patterns if (line.text.includes("drops")) { console.log(`Drop message: ${line.text}`); } }); } }, 600); } ``` -------------------------------- ### Find and Read Text - TypeScript Source: https://context7.com/skillbert/alt1/llms.txt Searches for and reads text within a defined image area using a specified font and colors. It can also read individual characters at exact coordinates or find the locations of specific characters. This is useful for dynamic UIs where text position might vary slightly. ```typescript import * as OCR from "alt1/ocr"; import * as a1lib from "alt1/base"; const font = require("alt1/fonts/aa_12px_mono.fontmeta.json"); const img = a1lib.capture(400, 200, 600, 400); const colors: OCR.ColortTriplet[] = [ [255, 255, 255], [255, 152, 31] ]; // Find and read text in an area const textResult = OCR.findReadLine(img, font, colors, 0, 0, 600, 400); if (textResult) { console.log(`Found text: ${textResult.text}`); console.log(`At position: (${textResult.fragments[0].xstart}, y)`); } // Read single character at exact location const char = OCR.readChar(img, font, [255, 255, 255], 50, 10, false, false); if (char) { console.log(`Character: ${char.chr}, confidence: ${char.score}`); } // Find character locations const charLoc = OCR.findChar(img, font, [255, 255, 255], 0, 0, 600, 400); if (charLoc) { console.log(`Found character at (${charLoc.x}, ${charLoc.y})`); } ``` -------------------------------- ### Detect Text Color - TypeScript Source: https://context7.com/skillbert/alt1/llms.txt Detects the dominant or best matching color within a specified image region from a list of possible colors. It offers two methods: `getChatColor` for the best match and `getChatColorMono` for monochrome fonts, returning scores for each possible color. This is useful for identifying UI elements or status indicators based on their color. ```typescript import * as OCR from "alt1/ocr"; import * as a1lib from "alt1/base"; const img = a1lib.capture(100, 100, 300, 50); const possibleColors: OCR.ColortTriplet[] = [ [255, 255, 255], [0, 255, 0], [255, 255, 0], [255, 0, 0] ]; // Detect best matching color const detectedColor = OCR.getChatColor( img, { x: 0, y: 0, width: 300, height: 50 }, possibleColors ); if (detectedColor) { console.log(`Detected color: RGB(${detectedColor[0]}, ${detectedColor[1]}, ${detectedColor[2]})`); } // For monochrome fonts, get all matches with scores const monoResults = OCR.getChatColorMono( img, { x: 0, y: 0, width: 300, height: 50 }, possibleColors ); monoResults.forEach(result => { console.log(`Color ${result.col} score: ${result.score}`); }); ``` -------------------------------- ### Read Text with Known Position - TypeScript Source: https://context7.com/skillbert/alt1/llms.txt Reads text from a specified rectangular area of the screen using a given font and a set of target colors. It returns the detected text along with information about colored fragments within the text. This function is useful for parsing UI elements with predictable locations. ```typescript import * as OCR from "alt1/ocr"; import * as a1lib from "alt1/base"; // Load a font definition const chatFont = require("alt1/fonts/aa_8px.fontmeta.json"); // Capture text area const img = a1lib.capture(500, 300, 400, 30); // Define text colors to detect const colors: OCR.ColortTriplet[] = [ [255, 255, 255], // white [255, 255, 0], // yellow [0, 255, 0] // green ]; // Read text line const result = OCR.readLine(img, chatFont, colors, 0, 10, true, false); console.log(`Text: ${result.text}`); // Access colored fragments result.fragments.forEach(frag => { const [r, g, b] = frag.color; console.log(`"${frag.text}" at x=${frag.xstart} color=(${r},${g},${b})`); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.